import env from "../env";
import xhr from "../xhr";
import {
  isObject,
  isArray,
  isFunction,
  isString,
  isNumber,
  isBool,
  isInvalid,
} from "../util";
import {
  object,
  array,
  string,
  int,
  float,
  bool,
  findValue,
  deepCopy,
  delInvalidProp,
} from "../util";
import {
  toTimeString,
  toMoneyString,
  toMagicImgURL,
  getURLQuery,
  mergeURL,
} from "../util";
import { cache, session, storage } from "../util";
import COS from "cos-js-sdk-v5";

export default {
  name: "plugin-user",
  profile: null,
  provinces: [],
  citys: [],
  countys: [],
  async call(...handles) {
    let res = undefined;
    for (let handle of handles) {
      if (isFunction(handle)) res = await handle(res);
      else res = await handle;
      if (isInvalid(res)) continue;
      if (res.code !== 0) break;
    }
    return res;
  },
  async post(url, data = {}, options = {}) {
    if (url in env.xhrNodes) url = env.xhrNodes[url];
    return xhr
      .post(
        url,
        data,
        Object.assign(options, {
          api: env.xhrPrefix,
          headers: Object.assign(object(options.headers), {
            session: storage([env.key, this.name, "session"]) || "666",
          }),
        })
      )
      .then((content) => {
        let { code, msg, data, total } = content;
        if (code === "CanceledError") [code, msg] = [-1, ""];
        else if (code === "AxiosError") [code, msg] = [-2, ""];
        else if (code === "Error") [code, msg] = [-3, ""];
        else if (data && Object.getPrototypeOf(data) === Object.prototype)
          [code, msg, data, total] = [
            data.code,
            data.msg,
            data.data,
            data.total,
          ];
        return {
          code,
          msg: msg || findValue(env.xhrErrors, "code", code, "msg", ""),
          data,
          total,
        };
      });
  },
  async getMCode(form = {}) {
    let res = await this.post("/user/pub/mcode.get", {
      phone: string(form.mobile),
    });
    if (res.code === 0) {
    }
    return res;
  },
  async login(form = {}) {
    let res = await this.post(
      "/user/pub/user.login",
      {
        loginType: bool(form.sms) ? "1" : "2", //登录方式：1为手机号，2为账号
        account: bool(form.sms) ? string(form.mobile) : string(form.number),
        password: bool(form.sms) ? null : string(form.password),
        verifySms: bool(form.sms) ? string(form.mcode) : null,
      },
      {
        after: (config) =>
          storage(
            [env.key, this.name, "session"],
            () => config.data.data.session
          ),
      }
    );
    if (res.code === 0) this.profile = null;
    return res;
  },
  async getClient(userId) {
    let res = await this.post("/client.get", { userId: string(userId) });
    if (res.code === 0) res.data = this.formatClient(res.data);
    return res;
  },
  async getClients(form = {}) {
    let res = await this.post("/app/user/userAccountList", {
      userId: this.profile.id,
      userAccount_exp:
        isString(form.number) && form.number
          ? [{ exp: "like", value: form.number }]
          : null,
      userName_exp:
        isString(form.name) && form.name
          ? [{ exp: "like", value: form.name }]
          : null,
      userGender: findValue(env.userSexs, "value", form.sex, "id"),
      userPhone_exp:
        isString(form.mobile) && form.mobile
          ? [{ exp: "like", value: form.mobile }]
          : null,
      userRole: findValue(env.userRoles, "value", form.role, "id"),
      deptIds:
        isArray(form.deptIds) && form.deptIds.length > 0
          ? form.deptIds.join()
          : isString(form.deptId)
          ? form.deptId || null
          : null,
      disableFlag: findValue(env.userBanneds, "value", form.banned, "id"),
      activateFlag: findValue(env.userEnable, "value", form.flag, "id"),
      orderBy: [{ order: "userId", by: "desc" }],
      pageSize: isNumber(form.linage) ? form.linage : 10,
      pageNum: isNumber(form.page) ? form.page : 1,
    });
    let data = object(res.data);
    if (res.code === 0)
      res.data = {
        list: array(data.list).map((data) => this.formatClient(data)),
        linage: Math.max(int(data.pageSize), 1),
        page: Math.max(int(data.pageNum), 1),
        total: Math.max(int(data.numberOfElements), 0),
      };
    return res;
  },

  async logout() {
    let res = await this.post("/user/pub/user.logout");
    if (res) this.profile = null;
    if (res) storage([env.key, this.name, "session"], "");
    return res;
  },

  async uploadFile(file, type, progress) {
    let config = {};
    return this.call(
      async () => {
        let res = await this.post("/user/file.upload1", {
          objType: findValue(env.fileTypes, "value", type, "id", ""),
          objName: file.name,
        });
        if (res.code === 0) config = object(res.data);
        return res;
      },
      async () => {
        let sign = object(config.sign);
        let credentials = object(sign.credentials);
        let getAuthorization = (options, callback) =>
          callback({
            TmpSecretId: credentials.tmpSecretId,
            TmpSecretKey: credentials.tmpSecretKey,
            XCosSecurityToken: credentials.sessionToken,
            StartTime: sign.startTime,
            ExpiredTime: sign.expiredTime,
          });
        let params = delInvalidProp({
          Bucket: config.bucket,
          Region: config.region,
          Key: config.key,
          Body: file,
          CacheControl: type === "image" ? "public" : "no-cache",
          ContentDisposition:
            (type === "document" ? "attachment" : "inline") +
            ";filename*=UTF-8''" +
            encodeURIComponent(file.name),
          onProgress: isFunction(progress)
            ? (data) =>
                progress({
                  total: int(data.total),
                  loaded: int(data.loaded),
                  percent: int(data.percent, 2),
                })
            : null,
        });
        let upload = (resolve) =>
          new COS({ getAuthorization }).putObject(params, (error, data) => {
            if (error) resolve({ code: error.code, msg: error.message });
            else resolve({ code: 0 });
          });
        return new Promise((resolve) => upload(resolve));
      },
      async () => {
        let res = await this.post("/user/file.upload2", {
          objType: findValue(env.fileTypes, "value", type, "id", ""),
          objName: file.name,
          objPath: config.key,
          objSize: file.size,
        });
        let data = object(res.data);
        if (res.code === 0) res.data = this.formatFile(res.data);
        return res;
      }
    );
  },
  formatFile(data = {}) {
    return {
      id: string(data.objId),
      type: findValue(env.fileTypes, "id", string(data.objType), "value", ""),
      name: string(data.objName).split("/").pop(),
      value: mergeURL(data.objPath, { id: string(data.objId) }),
      short: toMagicImgURL(data.objPath, 240, 240),
    };
  },
  async setClientMobile(client = {}, mobile) {
    let res = await this.post("/admin/userAccount/userAccountEditPhone", {
      userId: string(client.id),
      userPhone: string(mobile),
    });
    if (res.code === 0) {
    }
    return res;
  },
  async setClientPassword(client = {}, password) {
    let res = await this.post("/client/password.set", {
      userId: string(client.id),
      userPassword: string(password),
    });
    if (res.code === 0) {
    }
    return res;
  },
  formatClientDepment(data = {}) {
    return {
      id: string(data.id),
      client: this.formatClient(data.userIdUserAccount),
      dept: this.formatDept(data.deptIdDepartment),
      role: findValue(
        env.depmentRoles,
        "id",
        string(data.deptRole),
        "value",
        ""
      ),
      roleText: findValue(
        env.depmentRoles,
        "id",
        string(data.deptRole),
        "name",
        ""
      ),
      primary: findValue(
        env.depmentPrimarys,
        "id",
        string(data.deptAdmin),
        "value",
        ""
      ),
      primaryText: findValue(
        env.depmentPrimarys,
        "id",
        string(data.deptAdmin),
        "name",
        ""
      ),
      duty: string(data.deptDuty),
    };
  },
  async addClient(form = {}) {
    let res = await this.post("/client.add", {
      userAvatar: string(getURLQuery(form.avatar).id),
      userAccount: string(form.number),
      deptId: string(form.deptId),
      userName: string(form.name),
      userGender: findValue(env.userSexs, "value", form.sex, "id", ""),
      idNumber: string(form.sequence),
      userPhone: string(form.mobile),
      userRole: findValue(env.userRoles, "value", form.role, "id", ""),
      disableFlag: findValue(env.userBanneds, "value", form.banned, "id", ""),
    });
    if (res.code === 0) res.data = string(res.data);
    return res;
  },
  async addClientDepment(client = {}, dept = {}, form = {}) {
    let res = await this.post("/client/depment.add", {
      userId: string(client.id),
      deptId: string(dept.id),
      deptRole: findValue(env.depmentRoles, "value", form.role, "id", ""),
      deptDuty: string(form.duty),
      deptAdmin: findValue(
        env.depmentPrimarys,
        "value",
        form.primary,
        "id",
        ""
      ),
    });
    if (res.code === 0) {
    }
    return res;
  },
  async setClientDepment(client = {}, dept = {}, form = {}) {
    let res = await this.post("/client/depment.set", {
      id: string(form.id),
      deptId: string(dept.id),
      deptRole: findValue(env.depmentRoles, "value", form.role, "id", ""),
      deptDuty: isString(form.duty) && form.duty ? form.duty : null,
      deptDuty_exp:
        isString(form.duty) && form.duty
          ? null
          : [{ exp: "isNull", value: "666" }],
      deptAdmin: findValue(
        env.depmentPrimarys,
        "value",
        form.primary,
        "id",
        ""
      ),
    });
    if (res.code === 0) {
    }
    return res;
  },
  async delClientDepment(...depments) {
    let res = await this.post("/client/depment.del", {
      ids: depments.map((depment) => depment.id).join(),
    });
    if (res.code === 0) {
    }
    return res;
  },
  async setClient(form = {}) {
    let res = await this.post("/client.set", {
      userId: string(form.id),
      userAvatar: string(getURLQuery(form.avatar).id),
      userAccount: string(form.number),
      userName: string(form.name),
      userRole: findValue(env.userRoles, "value", form.role, "id", ""),

      userGender: findValue(env.userSexs, "value", form.sex, "id", ""),
      idNumber: isString(form.sequence) && form.sequence ? form.sequence : null,
      idNumber_exp:
        isString(form.sequence) && form.sequence
          ? null
          : [{ exp: "isNull", value: "666" }],
      disableFlag: findValue(env.userBanneds, "value", form.banned, "id", ""),
      activateFlag: findValue(env.userEnable, "value", form.flag, "id", ""),
    });
    if (res.code === 0) {
    }
    return res;
  },
  formatUserProfile(data = {}) {
    return {
      id: string(data.userId),
      avatar: this.formatFile(data.userAvatarSysStorage),
      number: string(data.userAccount),
      name: string(data.userName),
      nick: string(data.userNickname),
      sex: findValue(env.userSexs, "id", string(data.userGender), "value", ""),
      sexText: findValue(
        env.userSexs,
        "id",
        string(data.userGender),
        "name",
        ""
      ),
      sequence: string(data.idNumber),
      mobile: string(data.userPhone),
      email: string(data.userEmail),
      isAdmin: string(data.isAdmin),
      isAdminT: string(data.isAdminT),
      role: findValue(env.userRoles, "id", string(data.userRole), "value", ""),
      roleText: findValue(
        env.userRoles,
        "id",
        string(data.userRole),
        "name",
        ""
      ),
      depments: array(data.userIdDeptRelList).map((data) =>
        this.formatDepment(data)
      ),
      employees: array(data.userIdCorpContactList)
        .filter((data) => string(data.type) === "1")
        .map((data) => this.formatEmployee(data)),
      helpers: array(data.userIdCorpContactList)
        .filter((data) => string(data.type) === "2")
        .map((data) => this.formatHelper(data)),
      session: string(data.session),
      lastActiveAt: toTimeString(int(data.lastActive), "YYYY-MM-DD hh:mm"),
      lastLoginAt: toTimeString(int(data.lastLogin), "YYYY-MM-DD hh:mm"),
      createdAt: toTimeString(int(data.createdTime), "YYYY-MM-DD hh:mm"),
    };
  },
  async getUserProfile() {
    let res = await this.post("/user/profile.get");
    if (res.code === 0) {
      let profile = this.formatUserProfile(res.data);
      if (profile.role === "holder")
        res = await this.post("/holder/profile.get");
      if (profile.role === "staff") res = await this.post("/staff/profile.get");
      if (profile.role === "officer")
        res = await this.post("/officer/profile.get");
    }
    if (res.code === 0)
      res.data = this.profile = Object.assign(
        object(this.profile),
        this.formatUserProfile(res.data)
      );
    return res;
  },
  async setUserPassword(form = {}) {
    let res = await this.post("/user/password.set", {
      oldPassword: string(form.password),
      newPassword: string(form.newpassword),
    });
    if (res.code === 0) {
    }
    return res;
  },
  formatUserTask(data = {}) {
    return {
      id: string(data.taskId),
      type: findValue(
        env.userTaskTypes,
        "id",
        string(data.taskType),
        "value",
        ""
      ),
      typeText: findValue(
        env.userTaskTypes,
        "id",
        string(data.taskType),
        "name",
        ""
      ),
      startAt: toTimeString(int(data.startTime), "Y年M月D日 hh:mm:ss"),
      endAt: toTimeString(int(data.endTime), "Y年M月D日 hh:mm:ss"),
      duration: ((stime, etime) =>
        (data.duration = Math.floor(
          Math.max(etime > 0 ? etime - stime : Date.now() - stime, 0) / 1000
        )))(int(data.startTime), int(data.endTime)),
      durationText: ((duration) => {
        let hours =
          duration >= 3600 ? Math.floor(duration / 3600) + "小时" : "";
        let minutes =
          duration >= 60
            ? Math.floor((duration % 3600) / 60) + "分钟"
            : duration + "秒";
        return hours + minutes;
      })(data.duration),
      result: ((type, result) => {
        if (/^export-/i.test(type)) {
          return { type: "export", url: string(result) };
        } else if (/^import-/i.test(type)) {
          let data = object(result);
          let [success, fails, url] = [
            int(data.successCount),
            int(data.errorRow),
            string(data.errorPath),
          ];
          return {
            type: "import",
            total: success + fails,
            success,
            fails,
            url,
          };
        } else {
          return {};
        }
      })(
        findValue(env.userTaskTypes, "id", string(data.taskType), "value", ""),
        data.taskResult
      ),
      expired: int(data.endTime) + 7 * 24 * 3600 * 1000 < Date.now(),
      status: findValue(
        env.userTaskStatus,
        "id",
        string(data.taskState),
        "value",
        ""
      ),
      statusText: findValue(
        env.userTaskStatus,
        "id",
        string(data.taskState),
        "name",
        ""
      ),
      createdAt: toTimeString(int(data.createdTime), "Y年M月D日 hh:mm:ss"),
    };
  },
  async getUserTasks(form = {}) {
    let res = await this.post("/user/tasks.get", {
      taskType: findValue(env.userTaskTypes, "value", form.type, "id"),
      taskState: findValue(env.userTaskStatus, "value", form.status, "id"),
      userId: string(() => this.profile.id) || "666",
      orderBy: [{ order: "taskId", by: "desc" }],
      pageSize: isNumber(form.linage) ? form.linage : 10,
      pageNum: isNumber(form.page) ? form.page : 1,
    });
    let data = object(res.data);
    if (res.code === 0)
      res.data = {
        list: array(data.list).map((data) => this.formatUserTask(data)),
        linage: Math.max(int(data.pageSize), 1),
        page: Math.max(int(data.pageNum), 1),
        total: Math.max(int(data.numberOfElements), 0),
      };
    return res;
  },
  formatProvince(data = {}) {
    return {
      id: string(data.areaId),
      name: string(data.name),
    };
  },
  async getProvinces(form = {}) {
    let provinces = this.provinces;
    if (provinces.length > 0) return { code: 0, data: provinces };
    let res = await this.post("/user/pub/provinces.get", {
      areaId_exp: [
        { exp: ">=", value: "450000" },
        { exp: "<=", value: "459999" },
      ],
      level: "1",
      orderBy: [{ order: "areaId", by: "asc" }],
      pageSize: 100,
      pageNum: 1,
    });
    let data = object(res.data);
    if (res.code === 0)
      res.data = this.provinces = array(data.list).map((data) =>
        this.formatProvince(data)
      );
    return res;
  },
  formatCity(data = {}) {
    // console.log(data);
    return {
      id: string(data.areaId),
      province: {
        id: string(data.parentId),
        name:
          string(() => data.parentIdSysArea.name) ||
          string(
            () =>
              this.provinces.find(
                (province) => province.id === string(data.parentId)
              ).name
          ),
      },
      name: string(data.name),
    };
  },
  async getCitys(form = {}) {
    let citys = this.citys;
    // console.log(citys);
    if (citys.length > 0) return { code: 0, data: citys };
    let res = await this.post("/user/pub/citys.get", {
      areaId_exp: [
        { exp: ">=", value: "450000" },
        { exp: "<=", value: "459999" },
      ],
      level: "2",
      orderBy: [{ order: "areaId", by: "asc" }],
      pageSize: 1000,
      pageNum: 1,
    });
    let data = object(res.data);
    if (res.code === 0)
      res.data = this.citys = array(data.list).map((data) =>
        this.formatCity(data)
      );
    // console.log(res);

    return res;
  },
  formatCounty(data = {}) {
    return {
      id: string(data.areaId),
      city: {
        id: string(data.parentId),
        name:
          string(() => data.parentIdSysArea.name) ||
          string(
            () =>
              this.citys.find((city) => city.id === string(data.parentId)).name
          ),
      },
      name: string(data.name),
    };
  },
  async getCountys(form = {}) {
    let countys = this.countys;
    // console.log(countys);
    if (countys.length > 0) return { code: 0, data: countys };
    let res = await this.post("/user/pub/countys.get", {
      areaId_exp: [
        { exp: ">=", value: "450000" },
        { exp: "<=", value: "459999" },
      ],
      level: "3",
      orderBy: [{ order: "areaId", by: "asc" }],
      pageSize: 10000,
      pageNum: 1,
    });
    let data = object(res.data);
    if (res.code === 0)
      res.data = this.countys = array(data.list).map((data) =>
        this.formatCounty(data)
      );
    // console.log(res);
    return res;
  },
  formatCompanyOfTag(data = {}) {
    return {
      id: string(data.tagId),
      name: string(data.tagName),
    };
  },
  async getCompanyOfTags() {
    let res = await this.post("/user/pub/company/of/tags.get", {
      orderBy: [
        { order: "tagSort", by: "desc" },
        { order: "tagId", by: "desc" },
      ],
      pageSize: 100,
      pageNum: 1,
    });
    let data = object(res.data);
    if (res.code === 0)
      res.data = array(data.list).map((data) => this.formatCompanyOfTag(data));
    return res;
  },
  formatOrderOfTag(data = {}) {
    return {
      id: string(data.tagId),
      name: string(data.tagName),
      selected: false,
    };
  },
  async getOrderOfTags() {
    let res = await this.post("/user/pub/order/of/tags.get", {
      orderBy: [
        { order: "tagSort", by: "desc" },
        { order: "tagId", by: "desc" },
      ],
      pageSize: 100,
      pageNum: 1,
    });
    let data = object(res.data);
    if (res.code === 0)
      res.data = array(data.list).map((data) => this.formatOrderOfTag(data));
    return res;
  },
  async getCbone(data) {
    let res = await this.post("/app/workUrging/urging", {
      type: string(data.type),
      transactionId: string(data.zId),
    });
    // if (res.code === 0) res.data = this.formatOrder(res.data);
    return res;
  },
  async importClientsHolder(form = {}) {
    let res = await this.post("/clients/holder.import", { files: form.file });
    if (res.code === 0) {
    }
    return res;
  },
  async importClientsOfficer(form = {}) {
    let res = await this.post("/clients/officer.import", { files: form.file });
    if (res.code === 0) {
    }
    return res;
  },
  formatClient(data = {}) {
    return {
      id: string(data.userId),
      avatar: toMagicImgURL(
        mergeURL(() => data.userAvatarSysStorage.objPath, {
          id: data.userAvatar,
        }),
        120,
        120
      ),

      number: string(data.userAccount),
      lastActiveAt: toTimeString(int(data.lastActive), "Y年M月D日 hh:mm"),
      lastLoginAt: toTimeString(int(data.lastLogin), "Y年M月D日 hh:mm"),
      createdAt: toTimeString(int(data.createdTime), "Y年M月D日 hh:mm"),
      name: string(data.userName),
      nick: string(data.userNickname),
      sex: findValue(env.userSexs, "id", string(data.userGender), "value", ""),
      sexText: findValue(
        env.userSexs,
        "id",
        string(data.userGender),
        "name",
        ""
      ),
      sequence: string(data.idNumber),
      mobile: string(data.userPhone),
      email: string(data.userEmail),
      role: findValue(env.userRoles, "id", string(data.userRole), "value", ""),
      roleText: findValue(
        env.userRoles,
        "id",
        string(data.userRole),
        "name",
        ""
      ),
      depments: array(data.userIdDeptRelList).map((data) =>
        this.formatDepment(data)
      ),
      employees: array(data.userIdCorpContactList)
        .filter((data) => string(data.type) === "1")
        .map((data) => this.formatEmployee(data)),
      helpers: array(data.userIdCorpContactList)
        .filter((data) => string(data.type) === "2")
        .map((data) => this.formatHelper(data)),
      flag: findValue(
        env.userEnable,
        "id",
        string(data.activateFlag),
        "value",
        ""
      ),
      bandFlag: findValue(
        env.userEnable,
        "id",
        string(data.activateFlag),
        "name",
        ""
      ),
      banned: findValue(
        env.userBanneds,
        "id",
        string(data.disableFlag),
        "value",
        ""
      ),
      bannedText: findValue(
        env.userBanneds,
        "id",
        string(data.disableFlag),
        "name",
        ""
      ),
    };
  },
  formatEmployee(data = {}) {
    return {
      id: string(data.id),
      company: this.formatCompany(
        data.corpIdCorpDetail || { corpId: data.corpId }
      ),
      client: this.formatClient(
        data.userIdUserAccount || { userId: data.userId }
      ),
      duty: string(data.duty),
    };
  },
  formatHelper(data = {}) {
    return {
      id: string(data.id),
      company: this.formatCompany(
        data.corpIdCorpDetail || { corpId: data.corpId }
      ),
      client: this.formatClient(
        data.userIdUserAccount || { userId: data.userId }
      ),
    };
  },
  formatDeptsss(data = {}) {
    return {
      id: string(data.deptId),
      type: findValue(env.deptTypes, "id", string(data.deptType), "value", ""),
      typeText: findValue(
        env.deptTypes,
        "id",
        string(data.deptType),
        "name",
        ""
      ),
      dept: {
        id: string(data.parentId),
        name: string(() => data.parentIdDepartment.deptName),
      },
      name: string(data.deptName),
      province: this.formatProvince(data.provinceIdSysArea),
      city: this.formatCity(data.cityIdSysArea),
      county: this.formatCounty(data.areaIdSysArea),
      depts: [],
      level: int(data.deptLevel),
      sort: int(data.deptSort),
      activated: false,
      expanded: false,
      selected: false,
      loaded: false,
    };
  },
  formatDept(data = {}) {
    return {
      id: string(data.deptId),
      type: findValue(env.deptTypes, "id", string(data.deptType), "value", ""),
      typeText: findValue(
        env.deptTypes,
        "id",
        string(data.deptType),
        "name",
        ""
      ),
      dept: {
        id:
          string(data.parentId) || string(() => data.parentIdDepartment.deptId),
        type: findValue(
          env.deptTypes,
          "id",
          string(() => data.parentIdDepartment.deptType),
          "value",
          ""
        ),
        typeText: findValue(
          env.deptTypes,
          "id",
          string(() => data.parentIdDepartment.deptType),
          "name",
          ""
        ),
        name: string(() => data.parentIdDepartment.deptName),
        depments: array(() => data.parentIdDepartment.deptIdDeptRelList).map(
          (data) => this.formatDepment(data)
        ),
        level: int(() => data.parentIdDepartment.deptLevel),
        expanded: false,
      },
      name: string(data.deptName),
      province: {
        id: string(() => data.provinceId),
        name: string(() => data.provinceIdSysArea.name),
      },
      city: {
        id: string(() => data.cityId),
        name: string(() => data.cityIdSysArea.name),
      },
      county: {
        id: string(() => data.areaId),
        name: string(() => data.areaIdSysArea.name),
      },
      depments: array(data.deptIdDeptRelList).map((data) =>
        this.formatDepment(data)
      ),
      clients: array(data.deptIdDeptRelList).map((data) =>
        this.formatClient(data.userIdUserAccount)
      ),
      depts: array(data.departmentChildList).map((data) =>
        this.formatDept(data)
      ),
      level: int(data.deptLevel),
      sort: int(data.deptSort),
      activated: false,
      expanded: false,
      selected: false,
    };
  },
  async getjbdw(form = {}) {
    let res = await this.post("admin/department/departmentList", {
      // userId:this.profile.id,
      parentId: string(form.deptId) || null,
      deptLevel: isNumber(form.level) ? form.level : null,
      orderBy: [{ order: "deptId", by: "asc" }],
      pageSize: isNumber(form.linage) ? form.linage : 10,
      pageNum: isNumber(form.page) ? form.page : 1,
    });
    let data = object(res.data);
    if (res.code === 0)
      res.data = {
        list: array(data.list).map((data) => this.formatDept(data)),
        linage: Math.max(int(data.pageSize), 1),
        page: Math.max(int(data.pageNum), 1),
        total: Math.max(int(data.numberOfElements), 0),
      };
    return res;
  },
  async getDepts(form = {}) {
    let res = await this.post("/depts.get", {
      // userId:this.profile.id,
      parentId: string(form.deptId) || null,
      deptLevel: isNumber(form.level) ? form.level : null,
      orderBy: [{ order: "deptId", by: "asc" }],
      pageSize: isNumber(form.linage) ? form.linage : 10,
      pageNum: isNumber(form.page) ? form.page : 1,
    });
    let data = object(res.data);
    if (res.code === 0)
      res.data = {
        list: array(data.list).map((data) => this.formatDept(data)),
        linage: Math.max(int(data.pageSize), 1),
        page: Math.max(int(data.pageNum), 1),
        total: Math.max(int(data.numberOfElements), 0),
      };
    return res;
  },

  async getDeptsother(form = {}) {
    let res = await this.post("/depts.get", {
      // userId:this.profile.id,
      parentId: string(form.deptId) || null,
      // deptLevel: isNumber(form.level) ? form.level : null,
      orderBy: [{ order: "deptId", by: "asc" }],
      pageSize: isNumber(form.linage) ? form.linage : 10,
      pageNum: isNumber(form.page) ? form.page : 1,
    });
    let data = object(res.data);
    if (res.code === 0)
      res.data = {
        list: array(data.list).map((data) => this.formatDept(data)),
        linage: Math.max(int(data.pageSize), 1),
        page: Math.max(int(data.pageNum), 1),
        total: Math.max(int(data.numberOfElements), 0),
      };
    return res;
  },
  formatDepment(data = {}) {
    return {
      user_id: string(data.user_id),
      id: string(data.id),
      deptRole: string(data.deptRole),
      dept: this.formatDept(data.deptIdDepartment),
      client: this.formatClient(data.userIdUserAccount),
      role: findValue(
        env.depmentRoles,
        "id",
        string(data.deptRole),
        "value",
        ""
      ),
      roleText: findValue(
        env.depmentRoles,
        "id",
        string(data.deptRole),
        "name",
        ""
      ),
      duty: string(data.deptDuty),
      user_name: string(data.user_name),
      user_role: string(data.user_role),
      user_account: string(data.user_account),
      primary: findValue(
        env.depmentPrimarys,
        "id",
        string(data.deptAdmin),
        "value",
        ""
      ),
      primaryText: findValue(
        env.depmentPrimarys,
        "id",
        string(data.deptAdmin),
        "name",
        ""
      ),
      selected: false,
    };
  },
  formatIndustry(data = {}) {
    return {
      id: string(data.id),
      name: string(data.name),
    };
  },
  formatCompany(data = {}) {
    return {
      id: string(data.corpId),
      type: findValue(
        env.companyTypes,
        "id",
        string(data.corpType),
        "value",
        ""
      ),
      typeText: findValue(
        env.companyTypes,
        "id",
        string(data.corpType),
        "name",
        ""
      ),
      // logo: this.formatFile(data.corpIconSysStorage),
      logo: toMagicImgURL(
        mergeURL(() => data.corpIconSysStorage.objPath, { id: data.corpIcon }),
        120,
        120
      ),
      xydm: string(data.xydm),
      fwxz: string(data.fwxz),
      name: string(data.corpName),
      desc: string(() => data.corpIdCorpIntroList[0].content),
      code: string(data.corpCode),
      owner: string(data.corpOwner),
      size: findValue(
        env.companySizes,
        "id",
        string(data.corpSize),
        "value",
        ""
      ),
      sizeText: findValue(
        env.companySizes,
        "id",
        string(data.corpSize),
        "name",
        ""
      ),
      province: this.formatProvince(data.provinceSysArea),
      city: this.formatCity(data.citySysArea),
      county: this.formatCounty(data.countySysArea),
      cert01: findValue(
        env.companyCert01s,
        "id",
        string(data.corpCert01),
        "value",
        ""
      ),
      cert01Text: findValue(
        env.companyCert01s,
        "id",
        string(data.corpCert01),
        "name",
        ""
      ),
      cert02: findValue(
        env.companyCert02s,
        "id",
        string(data.corpCert02),
        "value",
        ""
      ),
      cert02Text: findValue(
        env.companyCert02s,
        "id",
        string(data.corpCert02),
        "name",
        ""
      ),
      cert03: findValue(
        env.companyCert03s,
        "id",
        string(data.corpCert03),
        "value",
        ""
      ),
      cert03Text: findValue(
        env.companyCert03s,
        "id",
        string(data.corpCert03),
        "name",
        ""
      ),
      cert04: findValue(
        env.companyCert04s,
        "id",
        string(data.corpCert04),
        "value",
        ""
      ),
      cert04Text: findValue(
        env.companyCert04s,
        "id",
        string(data.corpCert04),
        "name",
        ""
      ),
      cert05: findValue(
        env.companyCert05s,
        "id",
        string(data.corpCert05),
        "value",
        ""
      ),
      cert05Text: findValue(
        env.companyCert05s,
        "id",
        string(data.corpCert05),
        "name",
        ""
      ),
      cert06: findValue(
        env.companyCert06s,
        "id",
        string(data.corpCert06),
        "value",
        ""
      ),
      cert06Text: findValue(
        env.companyCert06s,
        "id",
        string(data.corpCert06),
        "name",
        ""
      ),
      location: {
        lng: float(data.longitude, 6),
        lat: float(data.latitude, 6),
        coord: float(data.latitude, 6) + "," + float(data.longitude, 6),
        address: string(data.address),
        link: mergeURL("https://apis.map.qq.com/uri/v1/marker", {
          marker:
            "coord:" +
            float(data.latitude, 6) +
            "," +
            float(data.longitude, 6) +
            ";title:" +
            string(data.corpName) +
            ";addr:" +
            string(() => data.citySysArea.name) +
            string(() => data.countySysArea.name) +
            string(data.address),
        }),
      },
      industry: this.formatIndustry(data.industryIdSysIndustry),
      tag: this.formatCompanyOfTag(
        object(() => data.corpTagMappCorpTagMapList[0])
      ),
      depts: array(data.corpIdCorpCompetentList).map((data) =>
        this.formatDept(data.deptIdDepartment)
      ),
      employees: array(data.corpIdCorpContactList)
        .filter((data) => string(data.type) === "1")
        .map((data) => this.formatEmployee(data)),
      helpers: array(data.corpIdCorpContactList)
        .filter((data) => string(data.type) === "2")
        .map((data) => this.formatHelper(data)),
      attendance: this.formatAttendance(
        object(() => data.corpSign || data.corpIdCorpSignList[0])
      ),
      attendances: array(data.corpIdCorpSignList).map((data) =>
        this.formatAttendance(data)
      ),
      stats: {
        ordersTotal: int(data.workOrderCount),
        ordersFinishedYesTotal:
          int(data.workOrderCount) - int(data.workOrderCompleteFlag_1),
        ordersFinishedNotTotal: int(data.workOrderCompleteFlag_1),
      },
      status: findValue(
        env.companyStatus,
        "id",
        string(data.status),
        "value",
        ""
      ),
      statusText: findValue(
        env.companyStatus,
        "id",
        string(data.status),
        "name",
        ""
      ),
      creator: this.formatClient(data.createdUserUserAccount),
      createdAt: toTimeString(int(data.createdTime), "Y年M月D日 hh:mm").replace(
        new Date().getFullYear() + "年",
        ""
      ),
    };
  },
  async getCompanysnum() {
    let res = await this.post(
      "app/corpDetail/corpDetailWho?type=1&userId=" + this.profile.id
    );
    // console.log(res);
    return res;
  },

  async getCompanys(form = {}) {
    // console.log();

    let res = await this.post("/holder/companys.get", {
      corpId_exp:
        isArray(form.ids) && form.ids.length > 0
          ? [
              {
                exp: "in",
                parameterType: "Long",
                value: form.ids.join() || "666",
              },
            ]
          : null,
      corpName_exp: string(form.name)
        ? [{ exp: "like", value: string(form.name) }]
        : null,
      city: string(form.cityId) || null,
      city_exp: bool(form.city)
        ? [
            {
              exp: "in",
              parameterType: "Long",
              value:
                array(() =>
                  this.profile.depments
                    .filter((depment) => depment.dept.city.id)
                    .map((depment) => depment.dept.city.id)
                ).join() || "666",
            },
          ]
        : null,
      county: string(form.countyId) || null,
      tagId_exp: string(form.tagId)
        ? [{ exp: "==", value: string(form.tagId) }]
        : null,
      deptId_exp: bool(form.dept)
        ? [
            {
              exp: "in",
              parameterType: "Long",
              value:
                array(() =>
                  this.profile.depments.map((depment) => depment.dept.id)
                ).join() || "666",
            },
          ]
        : null,
      //deptId_exp:  null,
      userId_exp:
        bool(form.employee) || bool(form.helper)
          ? [{ exp: "==", value: string(() => this.profile.id) || "666" }]
          : null,
      status: findValue(env.companyStatus, "value", form.status, "id"),
      createdUser: bool(form.creator)
        ? string(() => this.profile.id) || "666"
        : null,
      corpSign_userId: bool(form.attendance)
        ? string(() => this.profile.id) || "666"
        : null,
      userId: string(this.profile.id),
      orderBy: [{ order: "corpId", by: "desc" }],
      pageSize: isNumber(form.linage) ? form.linage : 10,
      pageNum: isNumber(form.page) ? form.page : 1,
    });
    let data = object(res.data);
    if (res.code === 0)
      res.data = {
        list: array(data.list).map((data) => this.formatCompany(data)),
        linage: Math.max(int(data.pageSize), 1),
        page: Math.max(int(data.pageNum), 1),
        total: Math.max(int(data.numberOfElements), 0),
      };
    return res;
  },
  async getCompanysother(form = {}) {
    let res = await this.post("admin/corpDetail/corpDetailList", {
      corpId_exp:
        isArray(form.ids) && form.ids.length > 0
          ? [
              {
                exp: "in",
                parameterType: "Long",
                value: form.ids.join() || "666",
              },
            ]
          : null,
      corpType: findValue(env.companyTypes, "value", form.type, "id"),
      corpName_exp:
        isString(form.name) && form.name
          ? [{ exp: "like", value: form.name }]
          : null,
      corpSize: findValue(env.companySizes, "value", form.size, "id"),
      province: isString(form.provinceId) ? form.provinceId || null : null,
      city: isString(form.cityId) ? form.cityId || null : null,
      county: isString(form.countyId) ? form.countyId || null : null,
      tagId_exp:
        isString(form.tagId) && form.tagId
          ? [{ exp: "==", value: form.tagId }]
          : null,
      deptId_exp:
        isString(form.deptId) && form.deptId
          ? [{ exp: "==", value: form.deptId }]
          : null,
      corpContactUserId_exp:
        isString(form.clientId) && form.clientId
          ? [{ exp: "==", value: form.clientId }]
          : null,
      status: findValue(env.companyStatus, "value", form.status, "id"),
      orderBy: [{ order: "corpId", by: "desc" }],
      pageSize: isNumber(form.linage) ? form.linage : 10,
      pageNum: isNumber(form.page) ? form.page : 1,
    });
    let data = object(res.data);
    if (res.code === 0)
      res.data = {
        list: array(data.list).map((data) => this.formatCompany(data)),
        linage: Math.max(int(data.pageSize), 1),
        page: Math.max(int(data.pageNum), 1),
        total: Math.max(int(data.numberOfElements), 0),
      };
    return res;
  },
  async getAttendancesother(form = {}) {
    let res = await this.post("/attendances.get", {
      corpId: isString(form.companyId) ? form.companyId || null : null,
      userId: isString(form.clientId) ? form.clientId || null : null,
      orderBy: [{ order: "id", by: "desc" }],
      pageSize: isNumber(form.linage) ? form.linage : 10,
      pageNum: isNumber(form.page) ? form.page : 1,
    });
    let data = object(res.data);
    if (res.code === 0)
      res.data = {
        list: array(data.list).map((data) => this.formatAttendance(data)),
        linage: Math.max(int(data.pageSize), 1),
        page: Math.max(int(data.pageNum), 1),
        total: Math.max(int(data.numberOfElements), 0),
      };
    return res;
  },
  async exportCompanys(form = {}) {
    let res = await this.post("/holder/companys.export", {
      corpId_exp:
        isArray(form.ids) && form.ids.length > 0
          ? [
              {
                exp: "in",
                parameterType: "Long",
                value: form.ids.join() || "666",
              },
            ]
          : null,
      corpName_exp: string(form.name)
        ? [{ exp: "like", value: string(form.name) }]
        : null,
      city: string(form.cityId) || null,
      city_exp: bool(form.city)
        ? [
            {
              exp: "in",
              parameterType: "Long",
              value:
                array(() =>
                  this.profile.depments
                    .filter((depment) => depment.dept.city.id)
                    .map((depment) => depment.dept.city.id)
                ).join() || "666",
            },
          ]
        : null,
      county: string(form.countyId) || null,
      tagId_exp: string(form.tagId)
        ? [{ exp: "==", value: string(form.tagId) }]
        : null,
      deptId_exp: bool(form.dept)
        ? [
            {
              exp: "in",
              parameterType: "Long",
              value:
                array(() =>
                  this.profile.depments.map((depment) => depment.dept.id)
                ).join() || "666",
            },
          ]
        : null,
      userId_exp:
        bool(form.employee) || bool(form.helper)
          ? [{ exp: "==", value: string(() => this.profile.id) || "666" }]
          : null,
      status: findValue(env.companyStatus, "value", form.status, "id"),
      createdUser: bool(form.creator)
        ? string(() => this.profile.id) || "666"
        : null,
      corpSign_userId: bool(form.attendance)
        ? string(() => this.profile.id) || "666"
        : null,
      orderBy: [{ order: "corpId", by: "desc" }],
    });
    if (res.code === 0) {
    }
    return res;
  },
  async exportCompanysUsed(form = {}) {
    let res = await this.post("/holder/companys/used.export", {
      corpId_exp:
        isArray(form.ids) && form.ids.length > 0
          ? [
              {
                exp: "in",
                parameterType: "Long",
                value: form.ids.join() || "666",
              },
            ]
          : null,
      corpName_exp: string(form.name)
        ? [{ exp: "like", value: string(form.name) }]
        : null,
      city: string(form.cityId) || null,
      city_exp: bool(form.city)
        ? [
            {
              exp: "in",
              parameterType: "Long",
              value:
                array(() =>
                  this.profile.depments
                    .filter((depment) => depment.dept.city.id)
                    .map((depment) => depment.dept.city.id)
                ).join() || "666",
            },
          ]
        : null,
      county: string(form.countyId) || null,
      tagId_exp: string(form.tagId)
        ? [{ exp: "==", value: string(form.tagId) }]
        : null,
      deptId_exp: bool(form.dept)
        ? [
            {
              exp: "in",
              parameterType: "Long",
              value:
                array(() =>
                  this.profile.depments.map((depment) => depment.dept.id)
                ).join() || "666",
            },
          ]
        : null,
      userId_exp:
        bool(form.employee) || bool(form.helper)
          ? [{ exp: "==", value: string(() => this.profile.id) || "666" }]
          : null,
      status: findValue(env.companyStatus, "value", form.status, "id"),
      createdUser: bool(form.creator)
        ? string(() => this.profile.id) || "666"
        : null,
      corpSign_userId: bool(form.attendance)
        ? string(() => this.profile.id) || "666"
        : null,
      orderBy: [{ order: "corpId", by: "desc" }],
    });
    if (res.code === 0) {
    }
    return res;
  },
  async exportCompanysAttendances(form = {}) {
    let res = await this.post("/holder/companys/attendances.export", {
      corpId_exp:
        isArray(form.ids) && form.ids.length > 0
          ? [
              {
                exp: "in",
                parameterType: "Long",
                value: form.ids.join() || "666",
              },
            ]
          : null,
      corpName_exp: string(form.name)
        ? [{ exp: "like", value: string(form.name) }]
        : null,
      city: string(form.cityId) || null,
      city_exp: bool(form.city)
        ? [
            {
              exp: "in",
              parameterType: "Long",
              value:
                array(() =>
                  this.profile.depments
                    .filter((depment) => depment.dept.city.id)
                    .map((depment) => depment.dept.city.id)
                ).join() || "666",
            },
          ]
        : null,
      county: string(form.countyId) || null,
      tagId_exp: string(form.tagId)
        ? [{ exp: "==", value: string(form.tagId) }]
        : null,
      deptId_exp: bool(form.dept)
        ? [
            {
              exp: "in",
              parameterType: "Long",
              value:
                array(() =>
                  this.profile.depments.map((depment) => depment.dept.id)
                ).join() || "666",
            },
          ]
        : null,
      userId_exp:
        bool(form.employee) || bool(form.helper)
          ? [{ exp: "==", value: string(() => this.profile.id) || "666" }]
          : null,
      status: findValue(env.companyStatus, "value", form.status, "id"),
      createdUser: bool(form.creator)
        ? string(() => this.profile.id) || "666"
        : null,
      corpSign_userId: bool(form.attendance)
        ? string(() => this.profile.id) || "666"
        : null,
      orderBy: [{ order: "corpId", by: "desc" }],
    });
    if (res.code === 0) {
    }
    return res;
  },
  async exportCompanysOrders(form = {}) {
    let res = await this.post("/holder/companys/orders.export", {
      corpId_exp:
        isArray(form.ids) && form.ids.length > 0
          ? [
              {
                exp: "in",
                parameterType: "Long",
                value: form.ids.join() || "666",
              },
            ]
          : null,
      corpName_exp: string(form.name)
        ? [{ exp: "like", value: string(form.name) }]
        : null,
      city: string(form.cityId) || null,
      city_exp: bool(form.city)
        ? [
            {
              exp: "in",
              parameterType: "Long",
              value:
                array(() =>
                  this.profile.depments
                    .filter((depment) => depment.dept.city.id)
                    .map((depment) => depment.dept.city.id)
                ).join() || "666",
            },
          ]
        : null,
      county: string(form.countyId) || null,
      tagId_exp: string(form.tagId)
        ? [{ exp: "==", value: string(form.tagId) }]
        : null,
      deptId_exp: bool(form.dept)
        ? [
            {
              exp: "in",
              parameterType: "Long",
              value:
                array(() =>
                  this.profile.depments.map((depment) => depment.dept.id)
                ).join() || "666",
            },
          ]
        : null,
      userId_exp:
        bool(form.employee) || bool(form.helper)
          ? [{ exp: "==", value: string(() => this.profile.id) || "666" }]
          : null,
      status: findValue(env.companyStatus, "value", form.status, "id"),
      createdUser: bool(form.creator)
        ? string(() => this.profile.id) || "666"
        : null,
      corpSign_userId: bool(form.attendance)
        ? string(() => this.profile.id) || "666"
        : null,
      orderBy: [{ order: "corpId", by: "desc" }],
    });
    if (res.code === 0) {
    }
    return res;
  },
  async addCompany(form = {}) {
    let res = await this.post("/holder/company.add", {
      corpType: findValue(env.companyTypes, "value", form.type, "id", ""),
      corpIcon: string(getURLQuery(form.logo).id),
      corpName: string(form.name),
      xydm: string(form.xydm),
      fwxz: string(form.fwxz),
      corpCode: string(form.code),
      corpOwner: string(form.owner),
      corpSize: findValue(env.companySizes, "value", form.size, "id", ""),
      corpIntroContent: string(form.desc),
      province: string(() => form.province.id),
      city: string(() => form.city.id),
      county: string(() => form.county.id),
      longitude: float(() => form.location.lng, 6),
      latitude: float(() => form.location.lat, 6),
      address: string(() => form.location.address),
      industryName: string(() => form.industry.name),
      tagIds: string(() => form.tag.id),
      deptIds: array(form.depts)
        .map((dept) => dept.id)
        .join(),
      corpContacts: [
        ...array(form.employees).map((employee) => ({
          type: "1",
          userId: string(() => employee.client.id),
          userName: string(() => employee.client.name),
          userPhone: string(() => employee.client.mobile),
          duty: string(employee.duty),
        })),
        ...array(form.helpers).map((helper) => ({
          type: "2",
          userId: string(() => helper.user_id),
          duty: "",
        })),
      ],
      status: findValue(env.companyStatus, "value", form.status, "id", ""),
    });
    if (res.code === 0) {
    }
    return res;
  },
  async getCompany(companyId) {
    let res = await this.post("/user/company.get", {
      corpId: string(companyId),
    });
    if (res.code === 0) res.data = this.formatCompany(res.data);
    // console.log(res);
    return res;
  },
  async setCompany(form = {}) {
    console.log(this.profile.role);
    let holder = bool(() => this.profile.role === "holder");
    let officer = bool(() => this.profile.role === "officer");
    let staff = bool(() => this.profile.role === "staff");
    // console.log(form.helpers);
    let res = await (() => {
      if (holder || officer)
        return this.post("/holder/company.set", {
          corpId: string(form.id),
          corpType: findValue(env.companyTypes, "value", form.type, "id", ""),
          corpIcon: string(getURLQuery(form.logo).id),
          corpName: string(form.name),
          corpCode: string(form.code),
          corpOwner: string(form.owner),
          corpSize: findValue(env.companySizes, "value", form.size, "id", ""),
          corpIntroContent: string(form.desc),
          province: string(() => form.province.id),
          city: string(() => form.city.id),
          county: string(() => form.county.id),
          longitude: float(() => form.location.lng, 6),
          latitude: float(() => form.location.lat, 6),
          address: string(() => form.location.address),
          industryName: string(() => form.industry.name),
          tagIds: string(() => form.tag.id),
          deptIds: array(form.depts)
            .map((dept) => dept.id)
            .join(),
          corpContacts: [
            ...array(form.employees).map((employee) => ({
              type: "1",
              userId: string(() => employee.client.id),
              userName: string(() => employee.client.name),
              userPhone: string(() => employee.client.mobile),
              duty: string(employee.duty),
            })),
            ...array(form.helpers).map((helper) => ({
              type: "2",
              userId: string(() => helper.user_id || helper.client.id),
              duty: "",
            })),
          ],
          status: findValue(env.companyStatus, "value", form.status, "id", ""),
        });
      else if (staff)
        return this.post("/staff/company.set", {
          corpId: string(form.id),
          corpName: string(form.name),
          corpIntroContent: string(form.desc),
          corpCode: string(form.code),
          corpOwner: string(form.owner),
          corpCert01: findValue(
            env.companyCert01s,
            "value",
            form.cert01,
            "id",
            ""
          ),
          corpCert02: findValue(
            env.companyCert02s,
            "value",
            form.cert02,
            "id",
            ""
          ),
          corpCert03: findValue(
            env.companyCert03s,
            "value",
            form.cert03,
            "id",
            ""
          ),
          corpCert04: findValue(
            env.companyCert04s,
            "value",
            form.cert04,
            "id",
            ""
          ),
          corpCert05: findValue(
            env.companyCert05s,
            "value",
            form.cert05,
            "id",
            ""
          ),
          corpCert06: findValue(
            env.companyCert06s,
            "value",
            form.cert06,
            "id",
            ""
          ),
        });
      else return { code: 0 };
    })();
    if (res.code === 0) {
    }
    return res;
  },
  formatProduct(data = {}) {
    return {
      id: string(data.id),
      company: this.formatCompany(
        data.corpIdCorpDetail || { corpId: data.corpId }
      ),
      avatar: this.formatFile(data.prodCoverSysStorage),
      name: string(data.prodName),
      desc: string(data.prodIntro),
      sort: int(data.sort),
    };
  },
  async getProducts(form = {}) {
    let res = await this.post("/user/products.get", {
      corpId: string(form.companyId) || null,
      orderBy: [
        { order: "sort", by: "desc" },
        { order: "id", by: "desc" },
      ],
      pageSize: isNumber(form.linage) ? form.linage : 10,
      pageNum: isNumber(form.page) ? form.page : 1,
    });
    let data = object(res.data);
    if (res.code === 0)
      res.data = {
        list: array(data.list).map((data) => this.formatProduct(data)),
        linage: Math.max(int(data.pageSize), 1),
        page: Math.max(int(data.pageNum), 1),
        total: Math.max(int(data.numberOfElements), 0),
      };
    return res;
  },
  async addProduct(form = {}) {
    let res = await this.post("/staff/product.add", {
      corpId: string(() => form.company.id),
      prodCover: string(() => form.avatar.id),
      prodName: string(form.name),
      prodIntro: string(form.desc),
      sort: int(form.sort),
    });
    if (res.code === 0) {
    }
    return res;
  },
  async setProduct(form = {}) {
    let res = await this.post("/staff/product.set", {
      id: string(form.id),
      corpId: string(() => form.company.id),
      prodCover: string(() => form.avatar.id),
      prodName: string(form.name),
      prodIntro: string(form.desc),
      sort: int(form.sort),
    });
    if (res.code === 0) {
    }
    return res;
  },
  async delProduct(...products) {
    let res = await this.post("/staff/product.del", {
      ids: products.map((product) => product.id).join(),
    });
    if (res.code === 0) {
    }
    return res;
  },
  formatAttendance(data = {}) {
    return {
      id: string(data.id),
      company: {
        id: string(data.corpId),
        name: string(() => data.corpIdCorpDetail.corpName),
      },
      dept: {
        id: string(data.deptId),
        name: string(() => data.deptIdDepartment.deptName),
      },
      client: {
        id: string(data.userId),
        number: string(() => data.userIdUserAccount.userAccount),
        name: string(() => data.userIdUserAccount.userName),
      },
      startLocation: {
        lng: float(() => data.arrivalLocation.split(",")[1], 6),
        lat: float(() => data.arrivalLocation.split(",")[0], 6),
        coord: string(data.arrivalLocation),
        address: "",
        link: mergeURL("https://apis.map.qq.com/uri/v1/marker", {
          marker:
            "coord:" +
            float(() => data.arrivalLocation.split(",")[0], 6) +
            "," +
            float(() => data.arrivalLocation.split(",")[1], 6) +
            ";title:" +
            string(() => data.corpIdCorpDetail.corpName) +
            ";addr:" +
            toTimeString(int(data.arrivalTime), "Y年M月D日 hh:mm"),
        }),
      },
      startTime: int(data.arrivalTime),
      startAt: toTimeString(int(data.arrivalTime), "Y年M月D日 hh:mm").replace(
        new Date().getFullYear() + "年",
        ""
      ),
      endLocation: {
        lng: float(() => data.departureLocation.split(",")[1], 6),
        lat: float(() => data.departureLocation.split(",")[0], 6),
        coord: string(data.departureLocation),
        address: "",
        link: mergeURL("https://apis.map.qq.com/uri/v1/marker", {
          marker:
            "coord:" +
            float(() => data.departureLocation.split(",")[0], 6) +
            "," +
            float(() => data.departureLocation.split(",")[1], 6) +
            ";title:" +
            string(() => data.corpIdCorpDetail.corpName) +
            ";addr:" +
            toTimeString(int(data.departureTime), "Y年M月D日 hh:mm"),
        }),
      },
      endTime: int(data.departureTime),
      endAt: toTimeString(int(data.departureTime), "Y年M月D日 hh:mm").replace(
        new Date().getFullYear() + "年",
        ""
      ),
      files: string(data.attachment)
        .split(",")
        .map((objId) =>
          this.formatFile(
            object(() =>
              array(data.sysStorageList).find((data) => data.objId === objId)
            )
          )
        )
        .filter((file) => file.id && file.type),
    };
  },
  async getAttendances(form = {}) {
    let res = await this.post("/user/attendances.get", {
      corpId:
        isString(form.companyId) && form.companyId ? form.companyId : null,
      orderBy: [{ order: "id", by: "desc" }],
      pageSize: isNumber(form.linage) ? form.linage : 10,
      pageNum: isNumber(form.page) ? form.page : 1,
    });
    let data = object(res.data);
    if (res.code === 0)
      res.data = {
        list: array(data.list).map((data) => this.formatAttendance(data)),
        linage: Math.max(int(data.pageSize), 1),
        page: Math.max(int(data.pageNum), 1),
        total: Math.max(int(data.numberOfElements), 0),
      };
    return res;
  },
  async delAttendance(...attendances) {
    let res = await this.post("/holder/attendance.del", {
      ids: attendances.map((attendance) => attendance.id).join(),
    });
    if (res.code === 0) {
    }
    return res;
  },
  formatTrack(data = {}) {
    return {
      id: string(data.nodeId),
      type: findValue(
        env.orderTrackTypes,
        "id",
        string(data.nodeType),
        "value",
        ""
      ),
      typeText: findValue(
        env.orderTrackTypes,
        "id",
        string(data.nodeType),
        "name",
        ""
      ),
      content: string(data.nodeAnnotate),
      files: string(data.attachment)
        .split(",")
        .map((objId) =>
          this.formatFile(
            object(() =>
              array(data.sysStorageList).find((data) => data.objId === objId)
            )
          )
        )
        .filter((file) => file.id && file.type),
      dept: this.formatDept(data.deptIdDepartment),
      handler: this.formatClient(data.userIdUserAccount),
      copytos: array(data.flowIdWorkCcList).map((data) =>
        this.formatClient(data.userIdUserAccount)
      ),
      signs: array(data.flowIdWorkCountersignList).map((data) =>
        this.formatTrackSign(data)
      ),
      handling: findValue(
        env.orderTrackHandlings,
        "id",
        string(data.returnFlag),
        "value",
        ""
      ),
      handlingText: findValue(
        env.orderTrackHandlings,
        "id",
        string(data.returnFlag),
        "name",
        ""
      ),
      finished: findValue(
        env.orderTrackFinisheds,
        "id",
        string(data.nodeState),
        "value",
        ""
      ),
      finishedText: findValue(
        env.orderTrackFinisheds,
        "id",
        string(data.nodeState),
        "name",
        ""
      ),
      finishedAt: toTimeString(
        int(data.completeTime),
        "Y年M月D日 hh:mm"
      ).replace(new Date().getFullYear() + "年", ""),
      countdown: int(data.createdTime) + 86400 * 1000 * 3,
      countdownAt: ((countdown) => {
        let value = Math.ceil(Math.max(countdown - Date.now(), 0) / 1000);
        let days = Math.floor(value / 86400);
        let hours = Math.floor((value % 86400) / 3600);
        let minutes = Math.floor((value % 3600) / 60);
        let seconds = Math.floor(value % 60);
        let text =
          days + "天" + hours + "小时" + minutes + "分钟" + seconds + "秒";
        return value > 0
          ? text
              .replace("0天0小时0分钟", "")
              .replace("0天0小时", "")
              .replace("0天", "")
          : "";
      })(int(data.createdTime) + 86400 * 1000 * 3),
      createdAt: toTimeString(int(data.createdTime), "Y年M月D日 hh:mm").replace(
        new Date().getFullYear() + "年",
        ""
      ),
      isAdmin: string(data.isAdmin),
    };
  },
  formatTrackSign(data = {}) {
    return {
      id: string(data.id),
      type: findValue(
        env.orderTrackSignTypes,
        "id",
        string(data.type),
        "value",
        ""
      ),
      typeText: findValue(
        env.orderTrackSignTypes,
        "id",
        string(data.type),
        "name",
        ""
      ),
      content: string(data.annotate),
      files: string(data.attachment)
        .split(",")
        .map((objId) =>
          this.formatFile(
            object(() =>
              array(data.sysStorageList).find((data) => data.objId === objId)
            )
          )
        )
        .filter((file) => file.id && file.type),
      replyContent: string(data.replyAnnotate),
      replyFiles: string(data.replyAttachment)
        .split(",")
        .map((objId) =>
          this.formatFile(
            object(() =>
              array(data.sysStorageListReply).find(
                (data) => data.objId === objId
              )
            )
          )
        )
        .filter((file) => file.id && file.type),
      dept: this.formatDept(data.deptIdDepartment),
      handler: this.formatClient(data.userIdUserAccount),
      stime: int(data.endTime - data.startTime),

      duration: ((stime, etime, duration) => {
        if (stime > 0 && etime > 0)
          duration = Math.ceil(Math.max((etime - stime) / 60000, 0));
        else if (stime > 0)
          duration = Math.ceil(Math.max((Date.now() - stime) / 60000, 0));
        let days = duration >= 1440 ? Math.floor(duration / 1440) + "天" : "";
        let hours =
          duration >= 60 ? Math.floor((duration % 1440) / 60) + "小时" : "";
        let minutes = duration >= 0 ? Math.floor(duration % 60) + "分钟" : "";
        return days + hours + minutes;
      })(int(data.startTime), int(data.endTime), 0),
      finished: findValue(
        env.orderTrackSignFinisheds,
        "id",
        string(data.status),
        "value",
        ""
      ),
      finishedText: findValue(
        env.orderTrackSignFinisheds,
        "id",
        string(data.status),
        "name",
        ""
      ),
      finishedAt: toTimeString(int(data.endTime), "Y年M月D日 hh:mm").replace(
        new Date().getFullYear() + "年",
        ""
      ),
      createdAt: toTimeString(int(data.startTime), "Y年M月D日 hh:mm").replace(
        new Date().getFullYear() + "年",
        ""
      ),
      isAdmin: string(data.isAdmin),
    };
  },
  formatOrder(data = {}) {
    let userIdUserAccountsss;
    if (data.userIdUserAccount) {
      userIdUserAccountsss = data.userIdUserAccount.userIdDeptRelList;
    } else {
      userIdUserAccountsss = null;
    }
    return {
      nodeId: string(data.nodeId),
      bjlx: string(data.bjlx),
      bcqk: string(data.bcqk),
      id: string(data.orderId),
      level: string(data.level),
      fwxz: string(data.fwxz),
      wtly: string(data.wtly),
      creater: string(data.userId),
      tags: array(data.workTagMappWorkTagMapList).map((data) =>
        this.formatOrderOfTag(data)
      ),
      company: this.formatCompany(
        data.corpIdCorpDetail || { corpId: data.corpId }
      ),
      title: string(data.title),
      content: string(data.content),
      files: string(data.attachment)
        .split(",")
        .map((objId) =>
          this.formatFile(
            object(() =>
              array(data.sysStorageList).find((data) => data.objId === objId)
            )
          )
        )
        .filter((file) => file.id && file.type),
      tracks: array(data.orderIdWorkFlowList)
        .map((data) => this.formatTrack(data))
        .reverse(),
      dept: this.formatDept(data.deptIdDepartment),
      hand: this.formatDept(data.createDeptDepartment),
      handler: this.formatClient(data.handlerIdUserAccount),
      finishedAt: toTimeString(
        int(data.completeTime),
        "Y年M月D日 hh:mm"
      ).replace(new Date().getFullYear() + "年", ""),
      finishedContent: string(data.completeContent),
      evaluated: findValue(
        env.orderEvaluateds,
        "id",
        string(data.evaluationFlag),
        "value",
        ""
      ),
      evaluatedText: findValue(
        env.orderEvaluateds,
        "id",
        string(data.evaluationFlag),
        "name",
        ""
      ),
      evaluatedStars: int(() => data.orderIdWorkEvaluationList[0].grade),
      evaluatedContent: string(() => data.orderIdWorkEvaluationList[0].content),
      evaluatedCreator: this.formatClient(
        object(() => data.orderIdWorkEvaluationList[0].reviewerUserAccount)
      ),
      likes: int(data.countWorkOrderLike),
      liked: int(data.countWorkOrderLikeUser) > 0,
      status: findValue(
        env.orderStatus,
        "id",
        string(data.status),
        "value",
        ""
      ),
      statusText: findValue(
        env.orderStatus,
        "id",
        string(data.status),
        "name",
        ""
      ),
      creator: this.formatClient(data.userIdUserAccount),
      createdAt: toTimeString(int(data.createdTime), "Y年M月D日 hh:mm").replace(
        new Date().getFullYear() + "年",
        ""
      ),

      userIdDeptRelList: userIdUserAccountsss,
    };
  },
  async getOrders(form = {}) {
    // console.log(this.profile.isAdmin);
    let holder = bool(() => this.profile.role === "holder");
    let staff = bool(() => this.profile.role === "staff");
    let officer = bool(() => this.profile.role === "officer");
    let res = await (() => {
      if (holder || this.profile.isAdmin > 0)
        return this.post("/holder/orders.get", {
          type: int(string(form.type).replace("type", "")),
          level_exp:
            isString(form.level) && form.level
              ? [{ exp: "==", value: form.level }]
              : null,
          fwxz_exp:
            isString(form.fwxz) && form.fwxz
              ? [{ exp: "==", value: form.fwxz }]
              : null,
          corpName_exp:
            isString(form.companyName) && form.companyName
              ? [{ exp: "like", value: form.companyName }]
              : null,
          corpCity_exp:
            isString(form.companyCityId) && form.companyCityId
              ? [{ exp: "==", value: form.companyCityId }]
              : null,
          corpCounty_exp:
            isString(form.companyCountyId) && form.companyCountyId
              ? [{ exp: "==", value: form.companyCountyId }]
              : null,
          title_exp:
            isString(form.title) && form.title
              ? [{ exp: "like", value: form.title }]
              : null,
          content_exp:
            isString(form.content) && form.content
              ? [{ exp: "like", value: form.content }]
              : null,
          tagId_exp:
            isString(form.tagId) && form.tagId
              ? [{ exp: "==", value: form.tagId }]
              : null,
          createDept_exp:
            isString(form.handId) && form.handId
              ? [
                  { exp: ">=", value: form.handId },
                  { exp: "<=", value: form.handId },
                ]
              : null,
          evaluationFlag_exp: ((id) =>
            isString(id) && id
              ? [
                  { exp: ">=", value: id },
                  { exp: "<=", value: id },
                ]
              : null)(
            findValue(env.orderEvaluateds, "value", form.evaluated, "id")
          ),
          status_exp: ((id) =>
            isString(id) && id
              ? [
                  { exp: ">=", value: id },
                  { exp: "<=", value: id },
                ]
              : null)(findValue(env.orderStatus, "value", form.status, "id")),
          orderBy: [{ order: "orderId", by: "desc" }],
          createdTimeStart: form.createdTimeStart ?? null,
          createdTimeEnd: form.createdTimeEnd ?? null,
          completeTimeStart: form.completeTimeStart ?? null,
          completeTimeEnd: form.completeTimeEnd ?? null,
          jbdwId: form.jbdwId ? form.jbdwId : null,
          pageSize: isNumber(form.linage) ? form.linage : 10,
          pageNum: isNumber(form.page) ? form.page : 1,
        });
      else if (staff)
        return this.post("/staff/orders.get", {
          type: int(string(form.type).replace("type", "")),
          level_exp:
            isString(form.level) && form.level
              ? [{ exp: "==", value: form.level }]
              : null,
          fwxz_exp:
            isString(form.fwxz) && form.fwxz
              ? [{ exp: "==", value: form.fwxz }]
              : null,
          corpName_exp:
            isString(form.companyName) && form.companyName
              ? [{ exp: "like", value: form.companyName }]
              : null,
          corpCity_exp:
            isString(form.companyCityId) && form.companyCityId
              ? [{ exp: "==", value: form.companyCityId }]
              : null,
          corpCounty_exp:
            isString(form.companyCountyId) && form.companyCountyId
              ? [{ exp: "==", value: form.companyCountyId }]
              : null,
          title_exp:
            isString(form.title) && form.title
              ? [{ exp: "like", value: form.title }]
              : null,
          content_exp:
            isString(form.content) && form.content
              ? [{ exp: "like", value: form.content }]
              : null,
          tagId_exp:
            isString(form.tagId) && form.tagId
              ? [{ exp: "==", value: form.tagId }]
              : null,
          createDept_exp:
            isString(form.handId) && form.handId
              ? [
                  { exp: ">=", value: form.handId },
                  { exp: "<=", value: form.handId },
                ]
              : null,
          evaluationFlag_exp: ((id) =>
            isString(id) && id
              ? [
                  { exp: ">=", value: id },
                  { exp: "<=", value: id },
                ]
              : null)(
            findValue(env.orderEvaluateds, "value", form.evaluated, "id")
          ),
          status_exp: ((id) =>
            isString(id) && id
              ? [
                  { exp: ">=", value: id },
                  { exp: "<=", value: id },
                ]
              : null)(findValue(env.orderStatus, "value", form.status, "id")),
          orderBy: [{ order: "orderId", by: "desc" }],
          jbdwId: form.jbdwId ? form.jbdwId : null,
          pageSize: isNumber(form.linage) ? form.linage : 10,
          pageNum: isNumber(form.page) ? form.page : 1,
        });
      else if (officer)
        return this.post("/officer/orders.get", {
          type: int(string(form.type).replace("type", "")),
          level_exp:
            isString(form.level) && form.level
              ? [{ exp: "==", value: form.level }]
              : null,
          fwxz_exp:
            isString(form.fwxz) && form.fwxz
              ? [{ exp: "==", value: form.fwxz }]
              : null,
          corpName_exp:
            isString(form.companyName) && form.companyName
              ? [{ exp: "like", value: form.companyName }]
              : null,
          corpCity_exp:
            isString(form.companyCityId) && form.companyCityId
              ? [{ exp: "==", value: form.companyCityId }]
              : null,
          corpCounty_exp:
            isString(form.companyCountyId) && form.companyCountyId
              ? [{ exp: "==", value: form.companyCountyId }]
              : null,
          title_exp:
            isString(form.title) && form.title
              ? [{ exp: "like", value: form.title }]
              : null,
          content_exp:
            isString(form.content) && form.content
              ? [{ exp: "like", value: form.content }]
              : null,
          tagId_exp:
            isString(form.tagId) && form.tagId
              ? [{ exp: "==", value: form.tagId }]
              : null,
          createDept_exp:
            isString(form.handId) && form.handId
              ? [
                  { exp: ">=", value: form.handId },
                  { exp: "<=", value: form.handId },
                ]
              : null,
          evaluationFlag_exp: ((id) =>
            isString(id) && id
              ? [
                  { exp: ">=", value: id },
                  { exp: "<=", value: id },
                ]
              : null)(
            findValue(env.orderEvaluateds, "value", form.evaluated, "id")
          ),
          status_exp: ((id) =>
            isString(id) && id
              ? [
                  { exp: ">=", value: id },
                  { exp: "<=", value: id },
                ]
              : null)(findValue(env.orderStatus, "value", form.status, "id")),
          jbdwId: form.jbdwId ? form.jbdwId : null,
          orderBy: [{ order: "orderId", by: "desc" }],
          pageSize: isNumber(form.linage) ? form.linage : 10,
          pageNum: isNumber(form.page) ? form.page : 1,
        });
      else return { code: 0 };
    })();
    let data = object(res.data);
    if (res.code === 0)
      res.data = {
        list: array(data.list).map((data) => this.formatOrder(data)),
        linage: Math.max(int(data.pageSize), 1),
        page: Math.max(int(data.pageNum), 1),
        total: Math.max(int(data.numberOfElements), 0),
        stats: object(data.stats),
      };
    return res;
  },
  async exportOrders(form = {}) {
    let res = await this.post("/holder/orders.export", {
      type: int(string(form.type).replace("type", "")),
      orderId_exp:
        isArray(form.ids) && form.ids.length > 0
          ? [
              {
                exp: "in",
                parameterType: "Long",
                value: form.ids.join() || "666",
              },
            ]
          : null,
      corpId:
        isString(form.companyId) && form.companyId ? form.companyId : null,
      corpName_exp:
        isString(form.companyName) && form.companyName
          ? [{ exp: "like", value: form.companyName }]
          : null,
      corpCity_exp:
        isString(form.companyCityId) && form.companyCityId
          ? [{ exp: "==", value: form.companyCityId }]
          : null,
      corpCounty_exp:
        isString(form.companyCountyId) && form.companyCountyId
          ? [{ exp: "==", value: form.companyCountyId }]
          : null,
      title_exp:
        isString(form.title) && form.title
          ? [{ exp: "like", value: form.title }]
          : null,
      content_exp:
        isString(form.content) && form.content
          ? [{ exp: "like", value: form.content }]
          : null,
      tagId_exp:
        isString(form.tagId) && form.tagId
          ? [{ exp: "==", value: form.tagId }]
          : null,
      createDept_exp:
        isString(form.handId) && form.handId
          ? [
              { exp: ">=", value: form.handId },
              { exp: "<=", value: form.handId },
            ]
          : null,
      evaluationFlag_exp: ((id) =>
        isString(id) && id
          ? [
              { exp: ">=", value: id },
              { exp: "<=", value: id },
            ]
          : null)(
        findValue(env.orderEvaluateds, "value", form.evaluated, "id")
      ),
      status_exp: ((id) =>
        isString(id) && id
          ? [
              { exp: ">=", value: id },
              { exp: "<=", value: id },
            ]
          : null)(findValue(env.orderStatus, "value", form.status, "id")),
      orderBy: [{ order: "orderId", by: "desc" }],
    });
    if (res.code === 0) {
    }
    return res;
  },
  async exportOrdersother(form = {}) {
    let res = await this.post("admin/export/exportWorkOrderList", {
      level_exp:
        isString(form.level) && form.level
          ? [{ exp: "==", value: form.level }]
          : null,
      fwxz_exp:
        isString(form.fwxz) && form.fwxz
          ? [{ exp: "==", value: form.fwxz }]
          : null,
      orderId_exp:
        isArray(form.ids) && form.ids.length > 0
          ? [
              {
                exp: "in",
                parameterType: "Long",
                value: form.ids.join() || "666",
              },
            ]
          : null,
      tagId_exp:
        isString(form.tagId) && form.tagId
          ? [{ exp: "==", value: form.tagId }]
          : null,
      corpId: isString(form.companyId) ? form.companyId || null : null,
      corpName_exp:
        isString(form.companyName) && form.companyName
          ? [{ exp: "like", value: form.companyName }]
          : null,
      title_exp:
        isString(form.title) && form.title
          ? [{ exp: "like", value: form.title }]
          : null,
      content_exp:
        isString(form.content) && form.content
          ? [{ exp: "like", value: form.content }]
          : null,
      deptId: isString(form.deptId) ? form.deptId || null : null,
      evaluationFlag: findValue(
        env.orderEvaluateds,
        "value",
        form.evaluated,
        "id"
      ),
      status: findValue(env.orderStatus, "value", form.status, "id"),
      orderBy: [{ order: "orderId", by: "desc" }],
    });
    if (res.code === 0) {
    }
    return res;
  },
  async addOrder(form = {}) {
    let holder = bool(() => this.profile.role === "holder");
    let staff = bool(() => this.profile.role === "staff");
    let res = await (() => {
      if (holder)
        return this.post("/holder/order.add", {
          workTags: array(form.tags)
            .map((tag) => tag.id)
            .join(),
          corpId: string(() => form.company.id),
          title: string(form.title),
          content: string(form.content),
          level: string(form.lev),
          xcbj: string(form.xcbj),
          wtly: string(form.wtly),

          fwxz: string(form.fwxz),
          attachment: array(form.files)
            .map((file) => string(file.id))
            .join(),
          deptId: string(() => form.dept.id),
          handlerId: string(() => form.handler.id),
          status: findValue(env.orderStatus, "value", form.status, "id", ""),
        });
      else if (staff)
        return this.post("/staff/order.add", {
          workTags: array(form.tags)
            .map((tag) => tag.id)
            .join(),
          corpId: string(() => form.company.id),
          title: string(form.title),
          level: string(form.lev),
          xcbj: string(form.xcbj),

          fwxz: string(form.fwxz),
          content: string(form.content),
          attachment: array(form.files)
            .map((file) => string(file.id))
            .join(),
          deptId: string(() => form.dept.id),
          handlerId: string(() => form.handler.id),
          status: findValue(env.orderStatus, "value", form.status, "id", ""),
        });
      else return { code: 0 };
    })();
    if (res.code === 0) res.data = this.formatOrder(res.data);
    return res;
  },
  async getOrder(orderId) {
    let res = await this.post("/user/order.get", { orderId: string(orderId) });
    if (res.code === 0) res.data = this.formatOrder(res.data);
    return res;
  },
  async setOrder(form = {}) {
    let holder = bool(() => this.profile.role === "holder");
    let staff = bool(() => this.profile.role === "staff");
    let res = await (() => {
      if (holder)
        return this.post("/holder/order.set", {
          orderId: string(form.id),
          level: string(form.level),
          workTags: array(form.tags)
            .map((tag) => tag.id)
            .join(),
          title: string(form.title),
          fwxz: string(form.fwxz),
          wtly: string(form.wtly),
          content: string(form.content),
          attachment:
            array(form.files).length > 0
              ? array(form.files)
                  .map((file) => string(file.id))
                  .join()
              : null,
          attachment_exp:
            array(form.files).length > 0
              ? null
              : [{ exp: "isNull", value: "666" }],
        });
      else if (staff)
        return this.post("/staff/order.set", {
          level: string(form.level),
          fwxz: string(form.fwxz),
          wtly: string(form.wtly),

          orderId: string(form.id),
          workTags: array(form.tags)
            .map((tag) => tag.id)
            .join(),
          title: string(form.title),
          content: string(form.content),
          attachment:
            array(form.files).length > 0
              ? array(form.files)
                  .map((file) => string(file.id))
                  .join()
              : null,
          attachment_exp:
            array(form.files).length > 0
              ? null
              : [{ exp: "isNull", value: "666" }],
          status: findValue(env.orderStatus, "value", form.status, "id", ""),
        });
      else return { code: 0 };
    })();
    if (res.code === 0) {
    }
    return res;
  },
  async delOrder(order) {
    let res = await this.post("/holder/order.del", { ids: string(order.id) });
    if (res.code === 0) {
    }
    return res;
  },
  async setOrderEvaluated(order = {}) {
    let res = await this.post("/staff/order/evaluated.set", {
      orderId: string(order.id),
      grade: int(order.evaluatedStars),
      content: string(order.evaluatedContent),
    });
    if (res.code === 0) {
    }
    return res;
  },
  async getOrderDepts(order = {}) {
    let res = await this.post("/holder/order/depts.get", {
      orderId: string(order.id) || "666",
    });
    if (res.code === 0)
      res.data = array(res.data).map((data) => this.formatDept(data));
    return res;
  },
  async getOrderDeptDepments(id) {
    let res = await this.post("/holder/order/dept/depments.get", {
      deptId: string(id) || "666",
      orderBy: [{ order: "id", by: "asc" }],
      pageSize: 100,
      pageNum: 1,
    });
    let data = object(res.data);
    if (res.code === 0)
      res.data = array(data.list).map((data) => this.formatDepment(data));
    // console.log(res);
    return res;
  },
  async getOrderDeptDepmentsObject(dept = {}) {
    let res = await this.post("/holder/order/dept/depments.get", {
      deptId: string(dept.id) || "666",
      orderBy: [{ order: "id", by: "asc" }],
      pageSize: 100,
      pageNum: 1,
    });
    let data = object(res.data);
    if (res.code === 0)
      res.data = array(data.list).map((data) => this.formatDepment(data));
    return res;
  },
  async getOrderDeptDepmentsObjectss(pageSize, pageNum) {
    let res = await this.post("app/corpV3/getLxfwldgb", {
      // deptId: string(dept) || "666",

      pageSize: pageSize,
      pageNum: pageNum,
    });
    var push = [];
    res.data.forEach((element) => {
      var role = "";
      if (element.user_role == 300) {
        role = "后援服务单位";
      } else if (element.user_role == 100) {
        role = "服务专员";
      }
      var obj = {
        dept_name: element.dept_name,
        user_account: element.user_account,
        user_id: element.user_id,
        user_name: element.user_name,
        user_role: role,
      };
      push.push(obj);
    });
    var resobj = {
      code: res.code,
      data: push,
      msg: res.msg,
      total: res.total,
    };
    return resobj;
  },
  async getOrderDeptDepmentskeyWord(keyword) {
    let res = await this.post("app/corpV3/getLxfwldgb", {
      // deptId: string(dept) || "666",

      keyWord: keyword,
    });
    var push = [];
    res.data.forEach((element) => {
      var role = "";
      if (element.user_role == 300) {
        role = "后援服务单位";
      } else if (element.user_role == 100) {
        role = "联系服务领导及联络员";
      }
      var obj = {
        dept_name: element.dept_name,
        user_account: element.user_account,
        user_id: element.user_id,
        user_name: element.user_name,
        user_role: role,
      };
      push.push(obj);
    });
    var resobj = {
      code: res.code,
      data: push,
      msg: res.msg,
      total: res.total,
    };
    return resobj;
  },
  formatOrderLiker(data = {}) {
    return {
      id: string(data.id),
      orderId: string(data.orderId),
      client: this.formatClient(data.userIdUserAccount),
      createdAt: toTimeString(int(data.createTime), "Y年M月D日 hh:mm").replace(
        new Date().getFullYear() + "年",
        ""
      ),
    };
  },
  async getOrderLikers(form = {}) {
    let res = await this.post("/user/order/likers.get", {
      orderId: isString(form.orderId) && form.orderId ? form.orderId : null,
      userAccount_exp:
        isString(form.clientNumber) && form.clientNumber
          ? [{ exp: "like", value: form.clientNumber }]
          : null,
      userName_exp:
        isString(form.clientName) && form.clientName
          ? [{ exp: "like", value: form.clientName }]
          : null,
      orderBy: [{ order: "id", by: "desc" }],
      pageSize: isNumber(form.linage) ? form.linage : 10,
      pageNum: isNumber(form.page) ? form.page : 1,
    });
    let data = object(res.data);
    if (res.code === 0)
      res.data = {
        list: array(data.list).map((data) => this.formatOrderLiker(data)),
        linage: Math.max(int(data.pageSize), 1),
        page: Math.max(int(data.pageNum), 1),
        total: Math.max(int(data.numberOfElements), 0),
        stats: object(data.stats),
      };
    return res;
  },
  async addOrderLiker(order = {}) {
    let res = await this.post("/user/order/liker.add", {
      orderId: string(order.id),
    });
    if (res.code === 0) {
    }
    return res;
  },
  async setOrderTrack(order = {}, track = {}) {
    let res = await this.post("/holder/order/track.set", {
      nodeId: string(track.id),
      nodeAnnotate: string(track.content) || null,
      nodeAnnotate_exp: string(track.content)
        ? null
        : [{ exp: "isNull", value: "666" }],
      attachment:
        array(track.files).length > 0
          ? array(track.files)
              .map((file) => string(file.id))
              .join()
          : null,
      attachment_exp:
        array(track.files).length > 0
          ? null
          : [{ exp: "isNull", value: "666" }],
    });
    if (res.code === 0) {
    }
    return res;
  },
  async startOrderTrack(order = {}, track = {}) {
    //联系服务领导及联络员拟办事项
    let res = await this.post("/holder/order/track.start", {
      nodeId: string(track.id),
      nodeAnnotate: string(track.content),
      attachment: array(track.files)
        .map((file) => string(file.id))
        .join(),
      flowUserId: string(() => track.handler.id),
      ccUserIds: array(track.copytos)
        .map((copyto) => copyto.id)
        .join(),
    });
    if (res.code === 0) res.data = this.formatOrder(res.data);
    return res;
  },
  async acceptOrderTrack(order = {}, track = {}) {
    //联系服务领导及联络员管理员受理事项
    let res = await this.post("/holder/order/track.accept", {
      nodeId: string(track.id),
      nodeAnnotate: string(track.content),
      attachment: array(track.files)
        .map((file) => string(file.id))
        .join(),
      flowUserId: string(() => track.handler.id),
      UserId: string(() => track.deptList.id),
      ccUserIds: array(track.copytos)
        .map((copyto) => copyto.id)
        .join(),
    });
    if (res.code === 0) res.data = this.formatOrder(res.data);
    return res;
  },
  async checkOrderTrack(order = {}, track = {}) {
    //联系服务领导及联络员队长审核事项
    let res = await this.post("/holder/order/track.check", {
      nodeId: string(track.id),
      nodeAnnotate: string(track.content),
      attachment: array(track.files)
        .map((file) => string(file.id))
        .join(),
      flowUserId: string(() => track.handler.id),
      ccUserIds: array(track.copytos)
        .map((copyto) => copyto.id)
        .join(),
    });
    if (res.code === 0) res.data = this.formatOrder(res.data);
    return res;
  },
  async upOrderTrack(order = {}, track = {}) {
    //联系服务领导及联络员管理员上报事项
    let res = await this.post("/holder/order/track.up", {
      nodeId: string(track.id),
      nodeAnnotate: string(track.content),
      attachment: array(track.files)
        .map((file) => string(file.id))
        .join(),
      flowUserId: string(() => track.handler.id),
      ccUserIds: array(track.copytos)
        .map((copyto) => copyto.id)
        .join(),
    });
    if (res.code === 0) res.data = this.formatOrder(res.data);
    return res;
  },
  async upOrderTrackV3(order = {}, track = {}) {
    //新流程上报事项

    let res = await this.post("/holder/order/track.up.v3", {
      nodeId: string(track.id),
      level: track.lev,
      nodeAnnotate: string(track.content),
      attachment: array(track.files)
        .map((file) => string(file.id))
        .join(),
      flowUserId: string(() => track.handler.id),
      ccUserIds: array(track.copytos)
        .map((copyto) => copyto.id)
        .join(),
    });
    if (res.code === 0) res.data = this.formatOrder(res.data);
    return res;
  },
  async getcountryList(params) {
    let res = await this.post("app/statisticsV3/statisticsOrderCounty", {
      fwxz: params.fwxz || "",
      tagId: params.tagId || "",
      countyId: params.areaId || "",
      pageNum: params.pageNum,
      pageSize: params.pageSize,
      status: params.status || "",
    });

    return res;
  },

  async getstatisticsOrderFwxz() {
    let res = await this.post("/app/statisticsV3/statisticsOrderFwxz", {});

    return res;
  },
  async getgroupranking(form = {}) {
    let res = await this.post("/app/big/data/completion/fwxz", {
      startTime: int(form.startTime) > 0 ? int(form.startTime) : 1685631599000,
      endTime: int(form.endTime) > 0 ? int(form.endTime) : 1985631599000,
      pageSize: 100,
      pageNum: 1,
    });

    return res;
  },
  async downOrderTrack(order = {}, track = {}) {
    //联系服务领导及联络员管理员下派事项
    // console.log(track.lev);
    let res = await this.post("/holder/order/track.down", {
      nodeId: string(track.id),
      level: track.lev,

      nodeAnnotate: string(track.content),
      attachment: array(track.files)
        .map((file) => string(file.id))
        .join(),
      flowDeptId: string(() => track.dept.id),
      flowUserId: string(() => track.handler.id),
      ccUserIds: array(track.copytos)
        .map((copyto) => copyto.id)
        .join(),
    });
    if (res.code === 0) res.data = this.formatOrder(res.data);
    return res;
  },
  async relayOrderTrack(order = {}, track = {}) {
    //联系服务领导及联络员管理员转派事项
    let res = await this.post("/holder/order/track.relay", {
      nodeId: string(track.id),
      flowCounterSigns: array(track.signs).map((sign) => ({
        annotate: string(sign.content),
        attachment: array(sign.files)
          .map((file) => string(file.id))
          .join(),
        deptId: string(() => sign.dept.id),
        userId: string(() => sign.handler.id),
      })),
      ccUserIds: array(track.copytos)
        .map((copyto) => copyto.id)
        .join(),
    });
    if (res.code === 0) res.data = this.formatOrder(res.data);
    return res;
  },
  async setOrderTrackSign(order = {}, track = {}, sign = {}) {
    let res = await this.post("/holder/order/track/sign.set", {
      id: string(sign.id),
      annotate: string(sign.content) || null,
      annotate_exp: string(sign.content)
        ? null
        : [{ exp: "isNull", value: "666" }],
      attachment:
        array(sign.files).length > 0
          ? array(sign.files)
              .map((file) => string(file.id))
              .join()
          : null,
      attachment_exp:
        array(sign.files).length > 0 ? null : [{ exp: "isNull", value: "666" }],
      replyAnnotate: string(sign.replyContent) || null,
      replyAnnotate_exp: string(sign.replyContent)
        ? null
        : [{ exp: "isNull", value: "666" }],
      replyAttachment:
        array(sign.replyFiles).length > 0
          ? array(sign.replyFiles)
              .map((file) => string(file.id))
              .join()
          : null,
      replyAttachment_exp:
        array(sign.replyFiles).length > 0
          ? null
          : [{ exp: "isNull", value: "666" }],
    });
    if (res.code === 0) {
    }
    return res;
  },
  async replyOrderTrackSign(order = {}, track = {}, sign = {}) {
    let res = await this.post("/officer/order/track/sign.reply", {
      id: string(sign.id),
      type: "1",
      replyAnnotate: string(sign.replyContent),
      replyAttachment: array(sign.replyFiles)
        .map((file) => string(file.id))
        .join(),
    });
    if (res.code === 0) res.data = this.formatOrder(res.data);
    return res;
  },
  async replyOrderTrackSignAdmin(order = {}, track = {}) {
    let res = await this.post("/officer/order/track/admin/sign.reply", {
      flowId: string(track.id),
      type: "1",
      replyAnnotate: string(track.content),
      replyAttachment: array(track.files)
        .map((file) => string(file.id))
        .join(),
    });
    if (res.code === 0) res.data = this.formatOrder(res.data);
    return res;
  },
  async zaidafu(track = {}) {
    let res = await this.post("/govs/workOrderNew/againCountersign", {
      flowId: string(track.id),
      replyAnnotate: string(track.content),
      replyAttachment: array(track.files)
        .map((file) => string(file.id))
        .join(),
    });
    if (res.code === 0) res.data = this.formatOrder(res.data);
    return res;
  },

  async returnOrderTrackSign(order = {}, track = {}, sign = {}) {
    let res = await this.post("/officer/order/track/sign.return", {
      id: string(sign.id),
      type: "2",
      replyAnnotate: string(sign.replyContent),
      replyAttachment: array(sign.replyFiles)
        .map((file) => string(file.id))
        .join(),
    });
    if (res.code === 0) res.data = this.formatOrder(res.data);
    return res;
  },
  async revokeOrderTrackSign(order = {}, track = {}) {
    //联系服务领导及联络员管理员撤回事项转派
    let res = await this.post("/holder/order/track/sign.revoke", {
      nodeId: string(track.id),
    });
    if (res.code === 0) res.data = this.formatOrder(res.data);
    return res;
  },
  async replyOrderTrack(order = {}, track = {}) {
    //联系服务领导及联络员管理员答复事项
    let res = await this.post("/holder/order/track.reply", {
      nodeId: string(track.id),
      nodeAnnotate: string(track.content),
      attachment: array(track.files)
        .map((file) => string(file.id))
        .join(),
      flowUserId: string(() => track.handler.id),
      ccUserIds: array(track.copytos)
        .map((copyto) => copyto.id)
        .join(),
    });
    if (res.code === 0) res.data = this.formatOrder(res.data);
    return res;
  },
  async reviewOrderTrack(order = {}, track = {}) {
    //联系服务领导及联络员队长审查事项
    let res = await this.post("/holder/order/track.review", {
      nodeId: string(track.id),
      nodeAnnotate: string(track.content),
      attachment: array(track.files)
        .map((file) => string(file.id))
        .join(),
      flowUserId: string(() => track.handler.id),
      ccUserIds: array(track.copytos)
        .map((copyto) => copyto.id)
        .join(),
    });
    if (res.code === 0) res.data = this.formatOrder(res.data);
    return res;
  },
  async finishOrderTrack(order = {}, track = {}) {
    //联系服务领导及联络员办结事项
    let res = await this.post("/holder/order/track.finish", {
      nodeId: string(track.id),
      nodeAnnotate: string(track.content),
      attachment: array(track.files)
        .map((file) => string(file.id))
        .join(),
      ccUserIds: array(track.copytos)
        .map((copyto) => copyto.id)
        .join(),
    });
    if (res.code === 0) res.data = this.formatOrder(res.data);
    return res;
  },
  async returnOrderTrack(order = {}, track = {}) {
    //退回事项
    let res = await this.post("/holder/order/track.return", {
      nodeId: string(track.id),
      nodeAnnotate: string(track.content),
      attachment: array(track.files)
        .map((file) => string(file.id))
        .join(),
      ccUserIds: array(track.copytos)
        .map((copyto) => copyto.id)
        .join(),
    });
    if (res.code === 0) res.data = this.formatOrder(res.data);
    return res;
  },
  async revokeOrderTrack(order = {}, track = {}) {
    //联系服务领导及联络员撤回事项
    let res = await this.post("/holder/order/track.revoke", {
      nodeId: string(track.id),
    });
    if (res.code === 0) res.data = this.formatOrder(res.data);
    return res;
  },
  async revokeOrderHolderTrack(order = {}, track = {}) {
    //联系服务领导及联络员撤回事项
    let res = await this.post("/holder/order/track.revoke", {
      nodeId: string(track.id),
    });
    if (res.code === 0) res.data = this.formatOrder(res.data);
    return res;
  },
  async revokeOrderTrackGov(order = {}, track = {}) {
    let res = await this.post("/holder/order/track.revoke.gov", {
      nodeId: string(track.id),
    });
    if (res.code === 0) res.data = this.formatOrder(res.data);
    return res;
  },
  async getCompanyOrders(form = {}) {
    let res = await this.post("/user/company/orders.get", {
      corpId: string(form.companyId) || "666",
      title_exp:
        isString(form.title) && form.title
          ? [{ exp: "like", value: form.title }]
          : null,
      content_exp:
        isString(form.content) && form.content
          ? [{ exp: "like", value: form.content }]
          : null,
      evaluationFlag: findValue(
        env.orderEvaluateds,
        "value",
        form.evaluated,
        "id"
      ),
      status: findValue(env.orderStatus, "value", form.status, "id"),
      orderBy: [{ order: "orderId", by: "desc" }],
      pageSize: isNumber(form.linage) ? form.linage : 10,
      pageNum: isNumber(form.page) ? form.page : 1,
    });
    let data = object(res.data);
    if (res.code === 0)
      res.data = {
        list: array(data.list).map((data) => this.formatOrder(data)),
        linage: Math.max(int(data.pageSize), 1),
        page: Math.max(int(data.pageNum), 1),
        total: Math.max(int(data.numberOfElements), 0),
      };
    return res;
  },
  formatDemand(data = {}) {
    return {
      id: string(data.id),
      company: this.formatCompany(
        data.corpIdCorpDetail || { corpId: data.corpId }
      ),
      type: findValue(env.demandTypes, "id", string(data.type), "value", ""),
      typeText: findValue(env.demandTypes, "id", string(data.type), "name", ""),
      title: string(data.title),
      content: string(data.content),
      files: string(data.attachment)
        .split(",")
        .map((objId) =>
          this.formatFile(
            object(() =>
              array(data.sysStorageList).find((data) => data.objId === objId)
            )
          )
        )
        .filter((file) => file.id && file.type),
      contacts: {
        name: string(data.contactName),
        mobile: string(data.contactPhone),
      },
      views: int(data.hits),
      approved: findValue(
        env.demandApproveds,
        "id",
        string(data.status),
        "value",
        ""
      ),
      approvedText: findValue(
        env.demandApproveds,
        "id",
        string(data.status),
        "name",
        ""
      ),
      status: findValue(
        env.demandStatus,
        "id",
        string(data.demandState),
        "value",
        ""
      ),
      statusText: findValue(
        env.demandStatus,
        "id",
        string(data.demandState),
        "name",
        ""
      ),
      creator: this.formatClient(data.userIdUserAccount),
      createdAt: toTimeString(int(data.createdTime), "Y年M月D日 hh:mm"),
    };
  },
  async getDemands(form = {}) {
    let res = await this.post("/user/demands.get", {
      category: int(string(form.category).replace("type", "")),
      type: findValue(env.demandTypes, "value", form.type, "id"),
      title_exp:
        isString(form.title) && form.title
          ? [{ exp: "like", value: form.title }]
          : null,
      status: findValue(env.demandApproveds, "value", form.approved, "id"),
      demandState: findValue(env.demandStatus, "value", form.status, "id"),
      orderBy: [{ order: "id", by: "desc" }],
      pageSize: isNumber(form.linage) ? form.linage : 10,
      pageNum: isNumber(form.page) ? form.page : 1,
    });
    let data = object(res.data);
    if (res.code === 0)
      res.data = {
        list: array(data.list).map((data) => this.formatDemand(data)),
        linage: Math.max(int(data.pageSize), 1),
        page: Math.max(int(data.pageNum), 1),
        total: Math.max(int(data.numberOfElements), 0),
      };
    return res;
  },
  async addDept(form = {}) {
    // console.log(form.province);
    let res = await this.post("/dept.add", {
      deptType: findValue(env.deptTypes, "value", form.type, "id", ""),
      parentId: string(form.parentId),
      deptName: string(form.name),
      provinceId: string(form.province),
      cityId: string(form.city),
      areaId: string(form.county),
      deptLevel: int(form.level),
      deptSort: int(form.sort),
    });
    if (res.code === 0) res.data = string(res.data);
    return res;
  },
  async setDept(form = {}) {
    // console.log(form.province);
    let res = await this.post("/dept.set", {
      deptId: string(form.id),
      deptType: findValue(env.deptTypes, "value", form.type, "id", ""),
      deptType_exp: string(form.type)
        ? null
        : [{ exp: "isNull", value: "666" }],
      parentId: string(form.parentId),
      deptName: string(form.name),
      provinceId: string(form.province.id) || null,
      provinceId_exp: string(form.province)
        ? null
        : [{ exp: "isNull", value: "666" }],
      cityId: string(form.city) || null,
      cityId_exp: string(form.city) ? null : [{ exp: "isNull", value: "666" }],
      areaId: string(form.county) || null,
      areaId_exp: string(form.county)
        ? null
        : [{ exp: "isNull", value: "666" }],
      deptLevel: int(form.level),
      deptSort: int(form.sort),
    });
    if (res.code === 0) {
    }
    return res;
  },
  async delDept(...depts) {
    let res = await this.post("/dept.del", {
      ids: depts.map((dept) => dept.id).join(),
    });
    if (res.code === 0) {
    }
    return res;
  },
  async addDemand(form = {}) {
    let res = await this.post("/staff/demand.add", {
      corpId: string(() => form.company.id),
      type: findValue(env.demandTypes, "value", form.type, "id", ""),
      title: string(form.title),
      content: string(form.content),
      attachment: array(form.files)
        .map((file) => string(file.id))
        .join(),
      contactName: string(() => form.contacts.name),
      contactPhone: string(() => form.contacts.mobile),
      publishFlag: "1",
      demandState: "1",
    });
    if (res.code === 0) res.data = this.formatDemand({ id: res.data });
    return res;
  },
  async setDemandStatus(demand = {}, status) {
    let res = await this.post("/staff/demand/status.set", {
      id: string(demand.id),
    });
    if (res.code === 0) {
    }
    return res;
  },
  formatDemandRecord(data = {}) {
    return {
      id: string(data.id),
      type: findValue(
        env.demandRecordTypes,
        "id",
        string(data.type),
        "value",
        ""
      ),
      typeText: findValue(
        env.demandRecordTypes,
        "id",
        string(data.type),
        "name",
        ""
      ),
      content: string(data.content),
      creator: this.formatClient(data.userIdUserAccount),
      createdAt: toTimeString(int(data.createdTime), "Y年M月D日 hh:mm"),
    };
  },
  async getDemandRecords(form = {}) {
    let res = await this.post("/user/demand/records.get", {
      demandId: string(form.demandId) || "666",
      orderBy: [{ order: "id", by: "desc" }],
      pageSize: isNumber(form.linage) ? form.linage : 10,
      pageNum: isNumber(form.page) ? form.page : 1,
    });
    let data = object(res.data);
    if (res.code === 0)
      res.data = {
        list: array(data.list).map((data) => this.formatDemandRecord(data)),
        linage: Math.max(int(data.pageSize), 1),
        page: Math.max(int(data.pageNum), 1),
        total: Math.max(int(data.numberOfElements), 0),
      };
    return res;
  },
  async addDemandRecord(demand = {}, record = {}) {
    let res = await this.post("/user/demand/record.add", {
      demandId: string(demand.id),
      type: findValue(env.demandRecordTypes, "value", record.type, "id", ""),
      content: string(record.content),
    });
    if (res.code === 0) {
    }
    return res;
  },
  async getCompanyDemands(form = {}) {
    let res = await this.post("/user/demands.get", {
      category: int(string(form.category).replace("type", "")),
      corpId: string(form.companyId) || "666",
      type: findValue(env.demandTypes, "value", form.type, "id"),
      title_exp:
        isString(form.title) && form.title
          ? [{ exp: "like", value: form.title }]
          : null,
      status: findValue(env.demandApproveds, "value", form.approved, "id"),
      demandState: findValue(env.demandStatus, "value", form.status, "id"),
      orderBy: [{ order: "id", by: "desc" }],
      pageSize: isNumber(form.linage) ? form.linage : 10,
      pageNum: isNumber(form.page) ? form.page : 1,
    });
    let data = object(res.data);
    if (res.code === 0)
      res.data = {
        list: array(data.list).map((data) => this.formatDemand(data)),
        linage: Math.max(int(data.pageSize), 1),
        page: Math.max(int(data.pageNum), 1),
        total: Math.max(int(data.numberOfElements), 0),
      };
    return res;
  },
  async getStatsOrderCity(form = {}) {
    let res = await this.post("/stats/order-city.get", {
      areaId: isString(form.cityId) && form.cityId ? form.cityId : null,
      startTime: int(form.startTime) > 0 ? int(form.startTime) : null,
      endTime: int(form.endTime) > 0 ? int(form.endTime) : null,
    });
    if (res.code === 0) res.data = array(res.data);
    return res;
  },
  async getStatsOrderTeam(form = {}) {
    let res = await this.post("/stats/order-team.get", {
      deptType_exp: [{ exp: "in", value: "1,2" }],
      provinceId: "450000",
      cityId: isString(form.cityId) && form.cityId ? form.cityId : null,
      startTime: int(form.startTime) > 0 ? int(form.startTime) : null,
      endTime: int(form.endTime) > 0 ? int(form.endTime) : null,
      orderBy: [
        { order: "deptSort", by: "desc" },
        { order: "deptId", by: "asc" },
      ],
      pageSize: 1000,
      pageNum: 1,
    });
    if (res.code === 0) res.data = array(res.data);
    return res;
  },
  async getStatsOrderGovernment(form = {}) {
    let res = await this.post("/stats/order-government.get", {
      deptType: "3",
      provinceId: "450000",
      cityId: string(form.cityId) || null,
      areaId_exp: [{ exp: "isNull", value: "666" }],
      startTime: int(form.startTime) > 0 ? int(form.startTime) : null,
      endTime: int(form.endTime) > 0 ? int(form.endTime) : null,
      orderBy: [
        { order: "deptSort", by: "desc" },
        { order: "deptId", by: "asc" },
      ],
      pageSize: 10000,
      pageNum: 1,
    });
    if (res.code === 0) res.data = array(res.data);
    return res;
  },
  async getStatsOrderTag(form = {}) {
    let res = await this.post("/stats/order-tag.get", {
      startTime: int(form.startTime) > 0 ? int(form.startTime) : null,
      endTime: int(form.endTime) > 0 ? int(form.endTime) : null,
      orderBy: [
        { order: "tagSort", by: "desc" },
        { order: "tagId", by: "desc" },
      ],
      pageSize: 1000,
      pageNum: 1,
    });
    if (res.code === 0) res.data = array(res.data);
    return res;
  },
  async getStatsAttendanceTeam(form = {}) {
    let res = await this.post("/stats/attendance-team.get", {
      deptType_exp: [{ exp: "in", value: "1,2" }],
      provinceId: "450000",
      cityId: isString(form.cityId) && form.cityId ? form.cityId : null,
      startTime: int(form.startTime) > 0 ? int(form.startTime) : null,
      endTime: int(form.endTime) > 0 ? int(form.endTime) : null,
      orderBy: [
        { order: "deptSort", by: "desc" },
        { order: "deptId", by: "asc" },
      ],
      pageSize: 1000,
      pageNum: 1,
    });
    if (res.code === 0) res.data = array(res.data);
    return res;
  },
  async getStatsEvaluationTeam(form = {}) {
    let res = await this.post("/stats/evaluation-team.get", {
      deptType_exp: [{ exp: "in", value: "1,2" }],
      provinceId: "450000",
      cityId: isString(form.cityId) && form.cityId ? form.cityId : null,
      startTime: int(form.startTime) > 0 ? int(form.startTime) : null,
      endTime: int(form.endTime) > 0 ? int(form.endTime) : null,
      orderBy: [
        { order: "deptSort", by: "desc" },
        { order: "deptId", by: "asc" },
      ],
      pageSize: 1000,
      pageNum: 1,
    });
    if (res.code === 0) res.data = array(res.data);
    return res;
  },
  async getStatsEvaluationGovernment(form = {}) {
    let res = await this.post("/stats/evaluation-government.get", {
      deptType: "3",
      provinceId: "450000",
      cityId: string(form.cityId) || null,
      areaId_exp: [{ exp: "isNull", value: "666" }],
      startTime: int(form.startTime) > 0 ? int(form.startTime) : null,
      endTime: int(form.endTime) > 0 ? int(form.endTime) : null,
      orderBy: [
        { order: "deptSort", by: "desc" },
        { order: "deptId", by: "asc" },
      ],
      pageSize: 10000,
      pageNum: 1,
    });
    if (res.code === 0) res.data = array(res.data);
    return res;
  },
  async getStatsArticlePolicy(form = {}) {
    let res = await this.post("/stats/article-policy.get", {
      parentId: "2",
      startTime: int(form.startTime) > 0 ? int(form.startTime) : null,
      endTime: int(form.endTime) > 0 ? int(form.endTime) : null,
      orderBy: [
        { order: "tagSort", by: "desc" },
        { order: "tagId", by: "desc" },
      ],
      pageSize: 100,
      pageNum: 1,
    });
    if (res.code === 0) res.data = array(res.data);
    return res;
  },
  async exportClientsHolder(form = {}) {
    let res = await this.post("/clients/holder.export", {
      deptType_exp: [{ exp: "in", value: "1,2" }],
      provinceId: "450000",
      cityId_exp: bool(() =>
        this.profile.depments.some(
          (depment) =>
            depment.dept.province.id &&
            !depment.dept.city.id &&
            !depment.dept.county.id
        )
      )
        ? null
        : [
            {
              exp: "in",
              value:
                array(() =>
                  this.profile.depments
                    .filter((depment) => depment.dept.city.id)
                    .map((depment) => depment.dept.city.id)
                ).join() || "666",
            },
          ],
    });
    if (res.code === 0) {
    }
    return res;
  },
  async getArticleOfTags(form = {}) {
    let res = await this.post("/article/of/tags.get", {
      orderBy: [
        { order: "tagSort", by: "desc" },
        { order: "tagId", by: "asc" },
      ],
      pageSize: isNumber(form.linage) ? form.linage : 10,
      pageNum: isNumber(form.page) ? form.page : 1,
    });
    let data = object(res.data);
    if (res.code === 0)
      res.data = {
        list: array(data.list).map((data) => this.formatArticleOfTag(data)),
        linage: Math.max(int(data.pageSize), 1),
        page: Math.max(int(data.pageNum), 1),
        total: Math.max(int(data.numberOfElements), 0),
      };
    return res;
  },
  async setArticle(form = {}) {
    let res = await this.post("/article.set", {
      articleId: string(form.id),
      articleCover: string(getURLQuery(form.banner).id),
      articleVideo: string(getURLQuery(form.video).id),
      articleTitle: string(form.title),
      articleAbstract: string(form.summary),
      articleContent: string(form.content),
      articleSource: string(form.referer),
      sourceLink: string(form.source),
      articleAuthor: string(form.author),
      articleEditor: string(form.editor),
      articleTagIds: (() => {
        let typeId = findValue(env.articleTypes, "value", form.type, "id", "");
        let tagId = string(() => form.tag.id);
        return tagId ? [typeId, tagId].join() : typeId;
      })(),
      articleWeight: int(form.weight),
      articlePublish: findValue(
        env.articlePublisheds,
        "value",
        form.published,
        "id",
        ""
      ),
    });
    if (res.code === 0) {
    }
    return res;
  },
  async getArticles(form = {}) {
    let res = await this.post("/articles.get", {
      articleTitle_exp:
        isString(form.title) && form.title
          ? [{ exp: "like", value: form.title }]
          : null,
      articleSource_exp:
        isString(form.referer) && form.referer
          ? [{ exp: "like", value: form.referer }]
          : null,
      articleAuthor_exp:
        isString(form.author) && form.author
          ? [{ exp: "like", value: form.author }]
          : null,
      tagId_exp: [
        {
          exp: "==",
          value:
            isString(form.tagId) && form.tagId
              ? form.tagId
              : findValue(env.articleTypes, "value", form.type, "id", "666"),
        },
      ],
      articlePublish: findValue(
        env.articlePublisheds,
        "value",
        form.published,
        "id"
      ),
      orderBy: [
        { order: "articleWeight", by: "desc" },
        { order: "updateTime", by: "desc" },
        { order: "articleId", by: "desc" },
      ],
      pageSize: isNumber(form.linage) ? form.linage : 10,
      pageNum: isNumber(form.page) ? form.page : 1,
    });
    let data = object(res.data);
    if (res.code === 0)
      res.data = {
        list: array(data.list).map((data) => this.formatArticle(data)),
        linage: Math.max(int(data.pageSize), 1),
        page: Math.max(int(data.pageNum), 1),
        total: Math.max(int(data.numberOfElements), 0),
      };
    return res;
  },
  async addArticle(form = {}) {
    let res = await this.post("/article.add", {
      articleCover: string(getURLQuery(form.banner).id),
      articleVideo: string(getURLQuery(form.video).id),
      articleTitle: string(form.title),
      articleAbstract: string(form.summary),
      articleContent: string(form.content),
      articleSource: string(form.referer),
      sourceLink: string(form.source),
      articleAuthor: string(form.author),
      articleEditor: string(form.editor),
      articleTagIds: (() => {
        let typeId = findValue(env.articleTypes, "value", form.type, "id", "");
        let tagId = string(() => form.tag.id);
        return tagId ? [typeId, tagId].join() : typeId;
      })(),
      startTime: int(form.startTime),
      endTime: int(form.endTime),
      articleWeight: int(form.weight),
      articlePublish: findValue(
        env.articlePublisheds,
        "value",
        form.published,
        "id",
        ""
      ),
    });
    if (res.code === 0) res.data = string(res.data);
    return res;
  },
  async getArticle(articleId) {
    let res = await this.post("/article.get", { articleId: string(articleId) });
    if (res.code === 0) res.data = this.formatArticle(res.data);
    return res;
  },
  // 已办成
  async postworkOrderSucceed(orderId) {
    let res = await this.post(
      `/app/workOrderNewV3/workOrderSucceed?orderId=${orderId}`
    );
    // if (res.code === 0) res.data = this.formatArticle(res.data);
    return res;
  },
  async addArticleOfTag(form = {}) {
    let res = await this.post("/article/of/tag.add", {
      parentId: string(() => form.tag.id),
      tagName: string(form.name),
      tagSort: int(form.sort),
    });
    if (res.code === 0) res.data = string(res.data);
    return res;
  },
  formatArticle(data = {}) {
    return {
      id: string(data.articleId),
      type: findValue(
        env.articleTypes,
        "id",
        string(
          () =>
            array(data.articleTagMappArticleTagMapList).find(
              (data) => string(data.parentId) === ""
            ).tagId
        ),
        "value",
        ""
      ),
      typeText: findValue(
        env.articleTypes,
        "id",
        string(
          () =>
            array(data.articleTagMappArticleTagMapList).find(
              (data) => string(data.parentId) === ""
            ).tagId
        ),
        "name",
        ""
      ),
      banner: toMagicImgURL(
        mergeURL(() => data.articleCoverSysStorage.objPath, {
          id: data.articleCover,
        }),
        120,
        120
      ),
      video: string(data.articleVideo)
        ? mergeURL(() => data.articleVideoSysStorage.objPath, {
            id: data.articleVideo,
          })
        : "",
      title: string(data.articleTitle),
      summary: string(data.articleAbstract),
      content: string(() => data.articleIdArticleContentList[0].content),
      referer: string(data.articleSource),
      source: string(data.sourceLink),
      author: string(data.articleAuthor),
      editor: string(data.articleEditor),
      tags: array(data.articleTagMappArticleTagMapList)
        .filter((data) => string(data.parentId))
        .map((data) => this.formatArticleOfTag(data)),
      tag: this.formatArticleOfTag(
        object(
          () =>
            array(data.articleTagMappArticleTagMapList).filter((data) =>
              string(data.parentId)
            )[0]
        )
      ),
      startTime: int(data.startTime) ? int(data.startTime) : null,

      startAt: toTimeString(int(data.startTime), "Y年M月D日"),
      endTime: int(data.endTime),
      endAt: toTimeString(int(data.endTime), "Y年M月D日"),
      weight: int(data.articleWeight),
      views: int(data.articleHits),
      clientRoleToPush: "",
      published: findValue(
        env.articlePublisheds,
        "id",
        string(data.articlePublish),
        "value",
        ""
      ),
      publishedText: findValue(
        env.articlePublisheds,
        "id",
        string(data.articlePublish),
        "name",
        ""
      ),
      createdAt: toTimeString(int(data.createdTime), "Y年M月D日 hh:mm"),
    };
  },
  formatArticleOfTag(data = {}) {
    return {
      id: string(data.tagId),
      tag: {
        id: string(data.parentId),
        name: string(() => data.parentIdArticleTag.tagName),
      },
      name: string(data.tagName),
      tags: [],
      level: 0,
      sort: int(data.tagSort),
      activated: false,
      expanded: false,
      selected: false,
    };
  },
  async exportClientsOfficer(form = {}) {
    let res = await this.post("/clients/officer.export", {
      deptType_exp: [{ exp: "in", value: "3" }],
      provinceId: "450000",
      cityId_exp: bool(() =>
        this.profile.depments.some(
          (depment) =>
            depment.dept.province.id &&
            !depment.dept.city.id &&
            !depment.dept.county.id
        )
      )
        ? null
        : [
            {
              exp: "in",
              value:
                array(() =>
                  this.profile.depments
                    .filter((depment) => depment.dept.city.id)
                    .map((depment) => depment.dept.city.id)
                ).join() || "666",
            },
          ],
    });
    if (res.code === 0) {
    }
    return res;
  },
  async getStatsArticleSjwt(form = {}) {
    let res = await this.post("/app/statisticsV3/district/zbtb1", {
      parentId: "2",
      startTime: int(form.startTime) > 0 ? int(form.startTime) : null,
      endTime: int(form.endTime) > 0 ? int(form.endTime) : null,
      orderBy: [
        { order: "tagSort", by: "desc" },
        { order: "tagId", by: "desc" },
      ],
      pageSize: 100,
      pageNum: 1,
    });
    if (res.code === 0) res.data = array(res.data);
    return res;
  },
  async getStatsArticleQqdy(form = {}) {
    let res = await this.post("/app/statisticsV3/district/zbtb2", {
      parentId: "2",
      startTime: int(form.startTime) > 0 ? int(form.startTime) : null,
      endTime: int(form.endTime) > 0 ? int(form.endTime) : null,
      orderBy: [
        { order: "tagSort", by: "desc" },
        { order: "tagId", by: "desc" },
      ],
      pageSize: 100,
      pageNum: 1,
    });
    if (res.code === 0) res.data = array(res.data);
    return res;
  },
  async getStatsArticleGzzb(form = {}) {
    let res = await this.post("/app/statisticsV3/district/zbtb3", {
      parentId: "2",
      startTime: int(form.startTime) > 0 ? int(form.startTime) : null,
      endTime: int(form.endTime) > 0 ? int(form.endTime) : null,
      orderBy: [
        { order: "tagSort", by: "desc" },
        { order: "tagId", by: "desc" },
      ],
      pageSize: 100,
      pageNum: 1,
    });
    if (res.code === 0) res.data = array(res.data);
    return res;
  },

  async getStatsArticleQjhb(form = {}) {
    let res = await this.post("/app/statisticsV3/district/zbtb4", {
      parentId: "2",
      startTime: int(form.startTime) > 0 ? int(form.startTime) : null,
      endTime: int(form.endTime) > 0 ? int(form.endTime) : null,
      orderBy: [
        { order: "tagSort", by: "desc" },
        { order: "tagId", by: "desc" },
      ],
      pageSize: 100,
      pageNum: 1,
    });
    if (res.code === 0) res.data = array(res.data);
    return res;
  },
  async init() {
    let res = await this.getUserProfile();
    if (res.code === 0) {
      await this.getProvinces();
      await this.getCitys();
      await this.getCountys();
      return res;
    } else {
      return { code: 2 };
    }
  },
};
